From 40fd4589c13bd45f76323cf04e9865266009eaeb Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Sat, 3 Feb 2018 02:09:20 +0100 Subject: [PATCH 01/15] init genesis WIP, also making golint compliant --- baseapp/baseapp.go | 35 +++++++++++++++------------ baseapp/baseapp_test.go | 2 +- baseapp/router.go | 6 +++++ baseapp/testapp.go | 11 ++++++++- examples/basecoin/app/app.go | 7 ++++-- examples/basecoin/app/init_baseapp.go | 10 ++++++++ 6 files changed, 52 insertions(+), 19 deletions(-) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 5ac7be1b50..409111d7f1 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -59,6 +59,7 @@ type BaseApp struct { var _ abci.Application = &BaseApp{} +// NewBaseApp - create and name new BaseApp func NewBaseApp(name string) *BaseApp { var baseapp = &BaseApp{ logger: makeDefaultLogger(), @@ -88,22 +89,26 @@ func (app *BaseApp) initMultiStore() { app.cms = cms } +// Name - BaseApp Name func (app *BaseApp) Name() string { return app.name } +// MountStore - Mount a store to the provided key in the BaseApp multistore func (app *BaseApp) MountStore(key sdk.StoreKey, typ sdk.StoreType) { app.cms.MountStoreWithDB(key, typ, app.db) } +// nolint func (app *BaseApp) SetTxDecoder(txDecoder sdk.TxDecoder) { app.txDecoder = txDecoder } - +func (app *BaseApp) SetInitStater(initStater sdk.InitStater) { + app.initStater = initStater +} func (app *BaseApp) SetDefaultAnteHandler(ah sdk.AnteHandler) { app.defaultAnteHandler = ah } - func (app *BaseApp) Router() Router { return app.router } @@ -111,25 +116,26 @@ func (app *BaseApp) Router() Router { /* TODO consider: func (app *BaseApp) SetBeginBlocker(...) {} func (app *BaseApp) SetEndBlocker(...) {} -func (app *BaseApp) SetInitStater(...) {} */ +// LoadLatestVersion - TODO add description func (app *BaseApp) LoadLatestVersion(mainKey sdk.StoreKey) error { app.cms.LoadLatestVersion() return app.initFromStore(mainKey) } +// LoadVersion - load application version func (app *BaseApp) LoadVersion(version int64, mainKey sdk.StoreKey) error { app.cms.LoadVersion(version) return app.initFromStore(mainKey) } -// The last CommitID of the multistore. +// LastCommitID - The last CommitID of the multistore. func (app *BaseApp) LastCommitID() sdk.CommitID { return app.cms.LastCommitID() } -// The last commited block height. +// LastBlockHeight - The last commited block height. func (app *BaseApp) LastBlockHeight() int64 { return app.cms.LastCommitID().Version } @@ -174,7 +180,7 @@ func (app *BaseApp) initFromStore(mainKey sdk.StoreKey) error { //---------------------------------------- -// Implements ABCI. +// Info - Implements ABCI func (app *BaseApp) Info(req abci.RequestInfo) abci.ResponseInfo { lastCommitID := app.cms.LastCommitID() @@ -186,13 +192,13 @@ func (app *BaseApp) Info(req abci.RequestInfo) abci.ResponseInfo { } } -// Implements ABCI. +// SetOption - Implements ABCI func (app *BaseApp) SetOption(req abci.RequestSetOption) (res abci.ResponseSetOption) { // TODO: Implement return } -// Implements ABCI. +// InitChain - Implements ABCI func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitChain) { // TODO: Use req.Validators return @@ -209,7 +215,7 @@ func (app *BaseApp) Query(req abci.RequestQuery) (res abci.ResponseQuery) { return queryable.Query(req) } -// Implements ABCI. +// BeginBlock - Implements ABCI func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeginBlock) { // NOTE: For consistency we should unset these upon EndBlock. app.header = &req.Header @@ -219,7 +225,7 @@ func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeg return } -// Implements ABCI. +// CheckTx - Implements ABCI func (app *BaseApp) CheckTx(txBytes []byte) (res abci.ResponseCheckTx) { // Decode the Tx. @@ -245,7 +251,7 @@ func (app *BaseApp) CheckTx(txBytes []byte) (res abci.ResponseCheckTx) { } -// Implements ABCI. +// DeliverTx - Implements ABCI func (app *BaseApp) DeliverTx(txBytes []byte) (res abci.ResponseDeliverTx) { // Decode the Tx. @@ -333,7 +339,7 @@ func (app *BaseApp) runTx(isCheckTx bool, txBytes []byte, tx sdk.Tx) (result sdk return result } -// Implements ABCI. +// EndBlock - Implements ABCI func (app *BaseApp) EndBlock(req abci.RequestEndBlock) (res abci.ResponseEndBlock) { res.ValidatorUpdates = app.valUpdates app.valUpdates = nil @@ -343,7 +349,7 @@ func (app *BaseApp) EndBlock(req abci.RequestEndBlock) (res abci.ResponseEndBloc return } -// Implements ABCI. +// Commit - Implements ABCI func (app *BaseApp) Commit() (res abci.ResponseCommit) { app.msDeliver.Write() commitID := app.cms.Commit() @@ -361,9 +367,8 @@ func (app *BaseApp) Commit() (res abci.ResponseCommit) { func (app *BaseApp) getMultiStore(isCheckTx bool) sdk.MultiStore { if isCheckTx { return app.msCheck - } else { - return app.msDeliver } + return app.msDeliver } // Return index of list with validator of same PubKey, or -1 if no match diff --git a/baseapp/baseapp_test.go b/baseapp/baseapp_test.go index 6e0f6c8e28..7ceaacd203 100644 --- a/baseapp/baseapp_test.go +++ b/baseapp/baseapp_test.go @@ -106,7 +106,7 @@ func TestBasic(t *testing.T) { } // Not matched. - j += 1 + j++ } } assert.Equal(t, len(valUpdates), 0, "Some validator updates were unexpected") diff --git a/baseapp/router.go b/baseapp/router.go index a15be84515..2f27d7a544 100644 --- a/baseapp/router.go +++ b/baseapp/router.go @@ -6,6 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" ) +// Router - TODO add description type Router interface { AddRoute(r string, h sdk.Handler) Route(path string) (h sdk.Handler) @@ -20,6 +21,9 @@ type router struct { routes []route } +// nolint +// NewRouter - create new router +// TODO either make Function unexported or make return type (router) Exported func NewRouter() *router { return &router{ routes: make([]route, 0), @@ -28,6 +32,7 @@ func NewRouter() *router { var isAlpha = regexp.MustCompile(`^[a-zA-Z]+$`).MatchString +// AddRoute - TODO add description func (rtr *router) AddRoute(r string, h sdk.Handler) { if !isAlpha(r) { panic("route expressions can only contain alphanumeric characters") @@ -35,6 +40,7 @@ func (rtr *router) AddRoute(r string, h sdk.Handler) { rtr.routes = append(rtr.routes, route{r, h}) } +// Route - TODO add description // TODO handle expressive matches. func (rtr *router) Route(path string) (h sdk.Handler) { for _, route := range rtr.routes { diff --git a/baseapp/testapp.go b/baseapp/testapp.go index c8708e222d..aa13c62b2d 100644 --- a/baseapp/testapp.go +++ b/baseapp/testapp.go @@ -17,6 +17,7 @@ type TestApp struct { *abci.ResponseEndBlock } +// NewTestApp - new app for tests func NewTestApp(bapp *BaseApp) *TestApp { app := &TestApp{ BaseApp: bapp, @@ -24,6 +25,7 @@ func NewTestApp(bapp *BaseApp) *TestApp { return app } +// RunBeginBlock - Execute BaseApp BeginBlock func (tapp *TestApp) RunBeginBlock() { if tapp.header != nil { panic("TestApp.header not nil, BeginBlock already run, or EndBlock not yet run.") @@ -56,36 +58,43 @@ func (tapp *TestApp) ensureBeginBlock() { } } +// RunCheckTx - run tx through CheckTx of TestApp func (tapp *TestApp) RunCheckTx(tx sdk.Tx) sdk.Result { tapp.ensureBeginBlock() return tapp.BaseApp.runTx(true, nil, tx) } +// RunDeliverTx - run tx through DeliverTx of TestApp func (tapp *TestApp) RunDeliverTx(tx sdk.Tx) sdk.Result { tapp.ensureBeginBlock() return tapp.BaseApp.runTx(false, nil, tx) } +// RunCheckMsg - run tx through CheckTx of TestApp // NOTE: Skips authentication by wrapping msg in testTx{}. func (tapp *TestApp) RunCheckMsg(msg sdk.Msg) sdk.Result { var tx = testTx{msg} return tapp.RunCheckTx(tx) } +// RunDeliverMsg - run tx through DeliverTx of TestApp // NOTE: Skips authentication by wrapping msg in testTx{}. func (tapp *TestApp) RunDeliverMsg(msg sdk.Msg) sdk.Result { var tx = testTx{msg} return tapp.RunDeliverTx(tx) } +// CommitMultiStore - return the commited multistore func (tapp *TestApp) CommitMultiStore() sdk.CommitMultiStore { return tapp.BaseApp.cms } +// MultiStoreCheck - return a cache-wrap CheckTx state of multistore func (tapp *TestApp) MultiStoreCheck() sdk.MultiStore { return tapp.BaseApp.msCheck } +// MultiStoreDeliver - return a cache-wrap DeliverTx state of multistore func (tapp *TestApp) MultiStoreDeliver() sdk.MultiStore { return tapp.BaseApp.msDeliver } @@ -97,11 +106,11 @@ type testTx struct { sdk.Msg } +// nolint func (tx testTx) GetMsg() sdk.Msg { return tx.Msg } func (tx testTx) GetSigners() []crypto.Address { return nil } func (tx testTx) GetFeePayer() crypto.Address { return nil } func (tx testTx) GetSignatures() []sdk.StdSignature { return nil } - func IsTestAppTx(tx sdk.Tx) bool { _, ok := tx.(testTx) return ok diff --git a/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index e87a2d7965..19de9e9e35 100644 --- a/examples/basecoin/app/app.go +++ b/examples/basecoin/app/app.go @@ -13,11 +13,12 @@ import ( const appName = "BasecoinApp" +// BasecoinApp - extended ABCI application type BasecoinApp struct { *bam.BaseApp router bam.Router cdc *wire.Codec - multiStore sdk.CommitMultiStore + multiStore sdk.CommitMultiStore //TODO distinguish this store from *bam.BaseApp.cms <- is this one master?? confused // The key to access the substores. capKeyMainStore *sdk.KVStoreKey @@ -27,6 +28,7 @@ type BasecoinApp struct { accountMapper sdk.AccountMapper } +// NewBasecoinApp - create new BasecoinApp // TODO: This should take in more configuration options. func NewBasecoinApp() *BasecoinApp { @@ -46,6 +48,7 @@ func NewBasecoinApp() *BasecoinApp { return app } +// RunForever - BasecoinApp execution and cleanup func (app *BasecoinApp) RunForever() { // Start the ABCI server @@ -64,7 +67,7 @@ func (app *BasecoinApp) RunForever() { } -// Load the stores. +// Load the stores func (app *BasecoinApp) loadStores() { if err := app.LoadLatestVersion(app.capKeyMainStore); err != nil { fmt.Println(err) diff --git a/examples/basecoin/app/init_baseapp.go b/examples/basecoin/app/init_baseapp.go index 35033aa99d..6cc6887528 100644 --- a/examples/basecoin/app/init_baseapp.go +++ b/examples/basecoin/app/init_baseapp.go @@ -11,6 +11,7 @@ func (app *BasecoinApp) initBaseApp() { app.BaseApp = bapp app.router = bapp.Router() app.initBaseAppTxDecoder() + app.initBaseAppInitStater() } func (app *BasecoinApp) initBaseAppTxDecoder() { @@ -26,3 +27,12 @@ func (app *BasecoinApp) initBaseAppTxDecoder() { return tx, nil }) } + +// used to define the custom logic for initialization +func (app *BasecoinApp) initBaseAppInitStater() { + accountMapper := app.accountMapper + app.BaseApp.SetInitStater(func(ctx sdk.Context, stateJSON []byte) sdk.Error { + // TODO: parse JSON + //accountMapper.SetAccount(ctx, ...) + }) +} From 41ae60c1fb659c18e54b28377e4a7f57d4ffb56a Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Sun, 4 Feb 2018 21:20:49 +0100 Subject: [PATCH 02/15] working --- baseapp/baseapp.go | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 409111d7f1..121b4cfbf4 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -19,7 +19,7 @@ import ( var mainHeaderKey = []byte("header") -// BaseApp - The ABCI application +// The ABCI application type BaseApp struct { logger log.Logger @@ -59,7 +59,7 @@ type BaseApp struct { var _ abci.Application = &BaseApp{} -// NewBaseApp - create and name new BaseApp +// Create and name new BaseApp func NewBaseApp(name string) *BaseApp { var baseapp = &BaseApp{ logger: makeDefaultLogger(), @@ -89,12 +89,12 @@ func (app *BaseApp) initMultiStore() { app.cms = cms } -// Name - BaseApp Name +// BaseApp Name func (app *BaseApp) Name() string { return app.name } -// MountStore - Mount a store to the provided key in the BaseApp multistore +// Mount a store to the provided key in the BaseApp multistore func (app *BaseApp) MountStore(key sdk.StoreKey, typ sdk.StoreType) { app.cms.MountStoreWithDB(key, typ, app.db) } @@ -118,24 +118,24 @@ func (app *BaseApp) SetBeginBlocker(...) {} func (app *BaseApp) SetEndBlocker(...) {} */ -// LoadLatestVersion - TODO add description +// TODO add description func (app *BaseApp) LoadLatestVersion(mainKey sdk.StoreKey) error { app.cms.LoadLatestVersion() return app.initFromStore(mainKey) } -// LoadVersion - load application version +// Load application version func (app *BaseApp) LoadVersion(version int64, mainKey sdk.StoreKey) error { app.cms.LoadVersion(version) return app.initFromStore(mainKey) } -// LastCommitID - The last CommitID of the multistore. +// The last CommitID of the multistore. func (app *BaseApp) LastCommitID() sdk.CommitID { return app.cms.LastCommitID() } -// LastBlockHeight - The last commited block height. +// The last commited block height. func (app *BaseApp) LastBlockHeight() int64 { return app.cms.LastCommitID().Version } @@ -180,7 +180,7 @@ func (app *BaseApp) initFromStore(mainKey sdk.StoreKey) error { //---------------------------------------- -// Info - Implements ABCI +// Implements ABCI func (app *BaseApp) Info(req abci.RequestInfo) abci.ResponseInfo { lastCommitID := app.cms.LastCommitID() @@ -192,13 +192,13 @@ func (app *BaseApp) Info(req abci.RequestInfo) abci.ResponseInfo { } } -// SetOption - Implements ABCI +// Implements ABCI func (app *BaseApp) SetOption(req abci.RequestSetOption) (res abci.ResponseSetOption) { // TODO: Implement return } -// InitChain - Implements ABCI +// Implements ABCI func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitChain) { // TODO: Use req.Validators return @@ -215,7 +215,7 @@ func (app *BaseApp) Query(req abci.RequestQuery) (res abci.ResponseQuery) { return queryable.Query(req) } -// BeginBlock - Implements ABCI +// Implements ABCI func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeginBlock) { // NOTE: For consistency we should unset these upon EndBlock. app.header = &req.Header @@ -225,7 +225,7 @@ func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeg return } -// CheckTx - Implements ABCI +// Implements ABCI func (app *BaseApp) CheckTx(txBytes []byte) (res abci.ResponseCheckTx) { // Decode the Tx. @@ -251,7 +251,7 @@ func (app *BaseApp) CheckTx(txBytes []byte) (res abci.ResponseCheckTx) { } -// DeliverTx - Implements ABCI +// Implements ABCI func (app *BaseApp) DeliverTx(txBytes []byte) (res abci.ResponseDeliverTx) { // Decode the Tx. @@ -339,7 +339,7 @@ func (app *BaseApp) runTx(isCheckTx bool, txBytes []byte, tx sdk.Tx) (result sdk return result } -// EndBlock - Implements ABCI +// Implements ABCI func (app *BaseApp) EndBlock(req abci.RequestEndBlock) (res abci.ResponseEndBlock) { res.ValidatorUpdates = app.valUpdates app.valUpdates = nil @@ -349,7 +349,7 @@ func (app *BaseApp) EndBlock(req abci.RequestEndBlock) (res abci.ResponseEndBloc return } -// Commit - Implements ABCI +// Implements ABCI func (app *BaseApp) Commit() (res abci.ResponseCommit) { app.msDeliver.Write() commitID := app.cms.Commit() From da538a8bf69b78db9b555d928ead3fa398a14616 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Mon, 5 Feb 2018 01:59:11 +0100 Subject: [PATCH 03/15] more comments cleanup --- baseapp/baseapp.go | 13 ++++++++----- types/coin.go | 4 ++-- types/coin_test.go | 4 ++-- types/context.go | 28 ++++++++-------------------- types/errors.go | 18 +++++++----------- types/handler.go | 1 + types/signature.go | 1 + types/store.go | 18 ++++++++++-------- types/tx_msg.go | 7 +++++++ 9 files changed, 46 insertions(+), 48 deletions(-) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 121b4cfbf4..4e0f3e003e 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -35,26 +35,29 @@ type BaseApp struct { // Unmarshal []byte into sdk.Tx txDecoder sdk.TxDecoder - // Ante handler for fee and auth. + // Ante handler for fee and auth defaultAnteHandler sdk.AnteHandler - // Handle any kind of message. + // Handle any kind of message router Router //-------------------- // Volatile - // CheckTx state, a cache-wrap of `.cms`. + // CheckTx state, a cache-wrap of `.cms` msCheck sdk.CacheMultiStore - // DeliverTx state, a cache-wrap of `.cms`. + // DeliverTx state, a cache-wrap of `.cms` msDeliver sdk.CacheMultiStore // Current block header header *abci.Header - // Cached validator changes from DeliverTx. + // Cached validator changes from DeliverTx valUpdates []abci.Validator + + // function to + initStater sdk.InitStater } var _ abci.Application = &BaseApp{} diff --git a/types/coin.go b/types/coin.go index 620c2f2891..ad541b99bd 100644 --- a/types/coin.go +++ b/types/coin.go @@ -184,6 +184,7 @@ func (coins Coins) IsNotNegative() bool { return true } +// Returns the amount of a denom from coins func (coins Coins) AmountOf(denom string) int64 { switch len(coins) { case 0: @@ -192,9 +193,8 @@ func (coins Coins) AmountOf(denom string) int64 { coin := coins[0] if coin.Denom == denom { return coin.Amount - } else { - return 0 } + return 0 default: midIdx := len(coins) / 2 // 2:1, 3:1, 4:2 coin := coins[midIdx] diff --git a/types/coin_test.go b/types/coin_test.go index 03890aa3fa..b58578a25f 100644 --- a/types/coin_test.go +++ b/types/coin_test.go @@ -192,7 +192,7 @@ func TestAmountOf(t *testing.T) { cases := []struct { coins Coins amountOf int64 - amountOf_ int64 + amountOfSpace int64 amountOfGAS int64 amountOfMINERAL int64 amountOfTREE int64 @@ -210,7 +210,7 @@ func TestAmountOf(t *testing.T) { for _, tc := range cases { assert.Equal(t, tc.amountOf, tc.coins.AmountOf("")) - assert.Equal(t, tc.amountOf_, tc.coins.AmountOf(" ")) + assert.Equal(t, tc.amountOfSpace, tc.coins.AmountOf(" ")) assert.Equal(t, tc.amountOfGAS, tc.coins.AmountOf("GAS")) assert.Equal(t, tc.amountOfMINERAL, tc.coins.AmountOf("MINERAL")) assert.Equal(t, tc.amountOfTREE, tc.coins.AmountOf("TREE")) diff --git a/types/context.go b/types/context.go index 4dbf64c3e2..3c90b016a2 100644 --- a/types/context.go +++ b/types/context.go @@ -30,6 +30,7 @@ type Context struct { // it's probably not what you want to do. } +// create a new context func NewContext(ms MultiStore, header abci.Header, isCheckTx bool, txBytes []byte) Context { c := Context{ Context: context.Background(), @@ -45,6 +46,7 @@ func NewContext(ms MultiStore, header abci.Header, isCheckTx bool, txBytes []byt return c } +// is context nil func (c Context) IsZero() bool { return c.Context == nil } @@ -52,6 +54,7 @@ func (c Context) IsZero() bool { //---------------------------------------- // Getting a value +// context value for the provided key func (c Context) Value(key interface{}) interface{} { value := c.Context.Value(key) if cloner, ok := value.(cloner); ok { @@ -71,34 +74,28 @@ func (c Context) KVStore(key StoreKey) KVStore { //---------------------------------------- // With* (setting a value) +// nolint func (c Context) WithValue(key interface{}, value interface{}) Context { return c.withValue(key, value) } - func (c Context) WithCloner(key interface{}, value cloner) Context { return c.withValue(key, value) } - func (c Context) WithCacheWrapper(key interface{}, value CacheWrapper) Context { return c.withValue(key, value) } - func (c Context) WithProtoMsg(key interface{}, value proto.Message) Context { return c.withValue(key, value) } - func (c Context) WithString(key interface{}, value string) Context { return c.withValue(key, value) } - func (c Context) WithInt32(key interface{}, value int32) Context { return c.withValue(key, value) } - func (c Context) WithUint32(key interface{}, value uint32) Context { return c.withValue(key, value) } - func (c Context) WithUint64(key interface{}, value uint64) Context { return c.withValue(key, value) } @@ -138,47 +135,38 @@ func (c Context) multiStore() MultiStore { return c.Value(contextKeyMultiStore).(MultiStore) } +// nolint func (c Context) BlockHeader() abci.Header { return c.Value(contextKeyBlockHeader).(abci.Header) } - func (c Context) BlockHeight() int64 { return c.Value(contextKeyBlockHeight).(int64) } - func (c Context) ChainID() string { return c.Value(contextKeyChainID).(string) } - func (c Context) IsCheckTx() bool { return c.Value(contextKeyIsCheckTx).(bool) } - func (c Context) TxBytes() []byte { return c.Value(contextKeyTxBytes).([]byte) } - func (c Context) WithMultiStore(ms MultiStore) Context { return c.withValue(contextKeyMultiStore, ms) } - func (c Context) WithBlockHeader(header abci.Header) Context { var _ proto.Message = &header // for cloning. return c.withValue(contextKeyBlockHeader, header) } - func (c Context) WithBlockHeight(height int64) Context { return c.withValue(contextKeyBlockHeight, height) } - func (c Context) WithChainID(chainID string) Context { return c.withValue(contextKeyChainID, chainID) } - func (c Context) WithIsCheckTx(isCheckTx bool) Context { return c.withValue(contextKeyIsCheckTx, isCheckTx) } - func (c Context) WithTxBytes(txBytes []byte) Context { return c.withValue(contextKeyTxBytes, txBytes) } @@ -199,6 +187,7 @@ type cloner interface { Clone() interface{} // deep copy } +// XXX add description type Op struct { // type is always 'with' gen int @@ -221,7 +210,7 @@ func newThePast() *thePast { func (pst *thePast) bump(op Op) { pst.mtx.Lock() - pst.ver += 1 + pst.ver++ pst.ops = append(pst.ops, op) pst.mtx.Unlock() } @@ -240,7 +229,6 @@ func (pst *thePast) getOp(ver int64) (Op, bool) { l := int64(len(pst.ops)) if l < ver || ver <= 0 { return Op{}, false - } else { - return pst.ops[ver-1], true } + return pst.ops[ver-1], true } diff --git a/types/errors.go b/types/errors.go index a878149313..2290ff833e 100644 --- a/types/errors.go +++ b/types/errors.go @@ -7,19 +7,20 @@ import ( "github.com/tendermint/go-crypto" ) +// ABCI Response Code type CodeType uint32 +// is everything okay? func (code CodeType) IsOK() bool { if code == CodeOK { return true - } else { - return false } + return false } +// ABCI Response Codes +// Base SDK reserves 0 ~ 99. const ( - // ABCI Response Codes - // Base SDK reserves 0 ~ 99. CodeOK CodeType = 0 CodeInternal CodeType = 1 CodeTxParse CodeType = 2 @@ -59,34 +60,28 @@ func CodeToDefaultMsg(code CodeType) string { // All errors are created via constructors so as to enable us to hijack them // and inject stack traces if we really want to. +// nolint func ErrInternal(msg string) Error { return newError(CodeInternal, msg) } - func ErrTxParse(msg string) Error { return newError(CodeTxParse, msg) } - func ErrBadNonce(msg string) Error { return newError(CodeBadNonce, msg) } - func ErrUnauthorized(msg string) Error { return newError(CodeUnauthorized, msg) } - func ErrInsufficientFunds(msg string) Error { return newError(CodeInsufficientFunds, msg) } - func ErrUnknownRequest(msg string) Error { return newError(CodeUnknownRequest, msg) } - func ErrUnrecognizedAddress(addr crypto.Address) Error { return newError(CodeUnrecognizedAddress, addr.String()) } - func ErrInvalidSequence(msg string) Error { return newError(CodeInvalidSequence, msg) } @@ -94,6 +89,7 @@ func ErrInvalidSequence(msg string) Error { //---------------------------------------- // Error & sdkError +// sdk Error type type Error interface { Error() string ABCICode() CodeType diff --git a/types/handler.go b/types/handler.go index 6b45f54739..129f42647a 100644 --- a/types/handler.go +++ b/types/handler.go @@ -1,5 +1,6 @@ package types +// core function variable which application runs for transactions type Handler func(ctx Context, msg Msg) Result // If newCtx.IsZero(), ctx is used instead. diff --git a/types/signature.go b/types/signature.go index e22d0c78cb..7fecc5fe96 100644 --- a/types/signature.go +++ b/types/signature.go @@ -2,6 +2,7 @@ package types import crypto "github.com/tendermint/go-crypto" +// Standard Signature type StdSignature struct { crypto.PubKey // optional crypto.Signature diff --git a/types/store.go b/types/store.go index 6802a4bf10..872c380901 100644 --- a/types/store.go +++ b/types/store.go @@ -9,12 +9,12 @@ import ( // NOTE: These are implemented in cosmos-sdk/store. -type Store interface { +type Store interface { //nolint GetStoreType() StoreType CacheWrapper } -// Something that can persist to disk. +// something that can persist to disk type Committer interface { Commit() CommitID LastCommitID() CommitID @@ -37,7 +37,7 @@ type Queryable interface { //---------------------------------------- // MultiStore -type MultiStore interface { +type MultiStore interface { //nolint Store // Cache wrap MultiStore. @@ -139,10 +139,6 @@ type CacheKVStore interface { cache-wraps make no sense. It can return KVStore, HeapStore, SpaceStore, etc. */ -type CacheWrapper interface { - CacheWrap() CacheWrap -} - type CacheWrap interface { // Write syncs with the underlying store. @@ -152,6 +148,10 @@ type CacheWrap interface { CacheWrap() CacheWrap } +type CacheWrapper interface { //nolint + CacheWrap() CacheWrap +} + //---------------------------------------- // CommitID @@ -161,7 +161,7 @@ type CommitID struct { Hash []byte } -func (cid CommitID) IsZero() bool { +func (cid CommitID) IsZero() bool { //nolint return cid.Version == 0 && len(cid.Hash) == 0 } @@ -172,9 +172,11 @@ func (cid CommitID) String() string { //---------------------------------------- // Store types +// kind of store type StoreType int const ( + //nolint StoreTypeMulti StoreType = iota StoreTypeDB StoreTypeIAVL diff --git a/types/tx_msg.go b/types/tx_msg.go index 8e7a8e4281..ebed8a25a6 100644 --- a/types/tx_msg.go +++ b/types/tx_msg.go @@ -4,6 +4,7 @@ import ( crypto "github.com/tendermint/go-crypto" ) +// Transactions messages must fulfill the Msg type Msg interface { // Return the message type. @@ -26,6 +27,7 @@ type Msg interface { GetSigners() []crypto.Address } +// Transactions objects must fulfill the Tx type Tx interface { // Gets the Msg. @@ -47,13 +49,18 @@ type Tx interface { var _ Tx = (*StdTx)(nil) +// standard transaction form type StdTx struct { Msg Signatures []StdSignature } +//nolint func (tx StdTx) GetMsg() Msg { return tx.Msg } func (tx StdTx) GetFeePayer() crypto.Address { return tx.Signatures[0].PubKey.Address() } func (tx StdTx) GetSignatures() []StdSignature { return tx.Signatures } +//------------------------------------- + +// Application function variable used to unmarshal transaction bytes type TxDecoder func(txBytes []byte) (Tx, Error) From 7643dea2555f5571bc64efe7bdd0523627b7399a Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Mon, 5 Feb 2018 02:41:55 +0100 Subject: [PATCH 04/15] genesis wip compiles --- examples/basecoin/app/init_baseapp.go | 3 ++- types/genesis.go | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 types/genesis.go diff --git a/examples/basecoin/app/init_baseapp.go b/examples/basecoin/app/init_baseapp.go index 6cc6887528..7ae6dd57d0 100644 --- a/examples/basecoin/app/init_baseapp.go +++ b/examples/basecoin/app/init_baseapp.go @@ -30,9 +30,10 @@ func (app *BasecoinApp) initBaseAppTxDecoder() { // used to define the custom logic for initialization func (app *BasecoinApp) initBaseAppInitStater() { - accountMapper := app.accountMapper + //accountMapper := app.accountMapper app.BaseApp.SetInitStater(func(ctx sdk.Context, stateJSON []byte) sdk.Error { // TODO: parse JSON //accountMapper.SetAccount(ctx, ...) + return nil }) } diff --git a/types/genesis.go b/types/genesis.go new file mode 100644 index 0000000000..995d2de574 --- /dev/null +++ b/types/genesis.go @@ -0,0 +1,4 @@ +package types + +// function variable used to initialize application state at genesis +type InitStater func(ctx Context, stateJSON []byte) Error From 6eaafa496af3a394094d8920ea2434d7b7c4b73b Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Wed, 7 Feb 2018 03:23:30 +0000 Subject: [PATCH 05/15] wip genesis parsing --- baseapp/baseapp.go | 16 +++++++------- baseapp/testapp.go | 17 +++++++-------- examples/basecoin/app/app_test.go | 31 +++++++++++++++++++++++++-- examples/basecoin/app/init_baseapp.go | 20 +++++++++++++---- types/errors.go | 18 ++++++++++------ 5 files changed, 73 insertions(+), 29 deletions(-) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 4e0f3e003e..80cd19eebe 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -32,13 +32,16 @@ type BaseApp struct { // Main (uncached) state cms sdk.CommitMultiStore - // Unmarshal []byte into sdk.Tx + // unmarshal []byte into sdk.Tx txDecoder sdk.TxDecoder - // Ante handler for fee and auth + // unmarshal rawjsonbytes to the initialize application + initStater sdk.InitStater + + // ante handler for fee and auth defaultAnteHandler sdk.AnteHandler - // Handle any kind of message + // handle any kind of message router Router //-------------------- @@ -50,14 +53,11 @@ type BaseApp struct { // DeliverTx state, a cache-wrap of `.cms` msDeliver sdk.CacheMultiStore - // Current block header + // current block header header *abci.Header - // Cached validator changes from DeliverTx + // cached validator changes from DeliverTx valUpdates []abci.Validator - - // function to - initStater sdk.InitStater } var _ abci.Application = &BaseApp{} diff --git a/baseapp/testapp.go b/baseapp/testapp.go index aa13c62b2d..389593d65a 100644 --- a/baseapp/testapp.go +++ b/baseapp/testapp.go @@ -17,7 +17,6 @@ type TestApp struct { *abci.ResponseEndBlock } -// NewTestApp - new app for tests func NewTestApp(bapp *BaseApp) *TestApp { app := &TestApp{ BaseApp: bapp, @@ -25,7 +24,7 @@ func NewTestApp(bapp *BaseApp) *TestApp { return app } -// RunBeginBlock - Execute BaseApp BeginBlock +// execute BaseApp BeginBlock func (tapp *TestApp) RunBeginBlock() { if tapp.header != nil { panic("TestApp.header not nil, BeginBlock already run, or EndBlock not yet run.") @@ -58,43 +57,43 @@ func (tapp *TestApp) ensureBeginBlock() { } } -// RunCheckTx - run tx through CheckTx of TestApp +// run tx through CheckTx of TestApp func (tapp *TestApp) RunCheckTx(tx sdk.Tx) sdk.Result { tapp.ensureBeginBlock() return tapp.BaseApp.runTx(true, nil, tx) } -// RunDeliverTx - run tx through DeliverTx of TestApp +// run tx through DeliverTx of TestApp func (tapp *TestApp) RunDeliverTx(tx sdk.Tx) sdk.Result { tapp.ensureBeginBlock() return tapp.BaseApp.runTx(false, nil, tx) } -// RunCheckMsg - run tx through CheckTx of TestApp +// run tx through CheckTx of TestApp // NOTE: Skips authentication by wrapping msg in testTx{}. func (tapp *TestApp) RunCheckMsg(msg sdk.Msg) sdk.Result { var tx = testTx{msg} return tapp.RunCheckTx(tx) } -// RunDeliverMsg - run tx through DeliverTx of TestApp +// run tx through DeliverTx of TestApp // NOTE: Skips authentication by wrapping msg in testTx{}. func (tapp *TestApp) RunDeliverMsg(msg sdk.Msg) sdk.Result { var tx = testTx{msg} return tapp.RunDeliverTx(tx) } -// CommitMultiStore - return the commited multistore +// return the commited multistore func (tapp *TestApp) CommitMultiStore() sdk.CommitMultiStore { return tapp.BaseApp.cms } -// MultiStoreCheck - return a cache-wrap CheckTx state of multistore +// return a cache-wrap CheckTx state of multistore func (tapp *TestApp) MultiStoreCheck() sdk.MultiStore { return tapp.BaseApp.msCheck } -// MultiStoreDeliver - return a cache-wrap DeliverTx state of multistore +// return a cache-wrap DeliverTx state of multistore func (tapp *TestApp) MultiStoreDeliver() sdk.MultiStore { return tapp.BaseApp.msDeliver } diff --git a/examples/basecoin/app/app_test.go b/examples/basecoin/app/app_test.go index 206257d2cc..15b98bd4ca 100644 --- a/examples/basecoin/app/app_test.go +++ b/examples/basecoin/app/app_test.go @@ -1,11 +1,17 @@ package app import ( + "encoding/json" "testing" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/x/bank" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/cosmos/cosmos-sdk/examples/basecoin/types" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + "github.com/cosmos/cosmos-sdk/x/bank" + crypto "github.com/tendermint/go-crypto" ) @@ -37,4 +43,25 @@ func TestSendMsg(t *testing.T) { // Run a Deliver on SendMsg. res = tba.RunDeliverMsg(msg) assert.Equal(t, sdk.CodeUnrecognizedAddress, res.Code, res.Log) + + // TODO seperate this test, need a closer on db? keep getting resource unavailable + + // construct some genesis bytes to reflect basecoin/types/AppAccount + pk := crypto.GenPrivKeyEd25519().PubKey() + addr := pk.Address() + coins, err := sdk.ParseCoins("77foocoin,99barcoin") + require.Nil(t, err) + baseAcc := auth.BaseAccount{ + Address: addr, + Coins: coins, + PubKey: pk, + Sequence: 0, + } + accs := []types.AppAccount{ + {baseAcc, "foobart"}, + {baseAcc, "endofzeworld"}, + } + bytes, err := json.MarshalIndent(&accs, "", "\t") + _ = bytes + // XXX test the json bytes in the InitStater } diff --git a/examples/basecoin/app/init_baseapp.go b/examples/basecoin/app/init_baseapp.go index 7ae6dd57d0..7b3bb7bcaa 100644 --- a/examples/basecoin/app/init_baseapp.go +++ b/examples/basecoin/app/init_baseapp.go @@ -1,7 +1,10 @@ package app import ( + "encoding/json" + "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/examples/basecoin/types" sdk "github.com/cosmos/cosmos-sdk/types" ) @@ -28,12 +31,21 @@ func (app *BasecoinApp) initBaseAppTxDecoder() { }) } -// used to define the custom logic for initialization +// define the custom logic for basecoin initialization func (app *BasecoinApp) initBaseAppInitStater() { - //accountMapper := app.accountMapper + accountMapper := app.accountMapper app.BaseApp.SetInitStater(func(ctx sdk.Context, stateJSON []byte) sdk.Error { - // TODO: parse JSON - //accountMapper.SetAccount(ctx, ...) + + var accs []*types.AppAccount + + err := json.Unmarshal(stateJSON, &accs) + if err != nil { + return sdk.ErrGenesisParse("").TraceCause(err, "") + } + + for _, acc := range accs { + accountMapper.SetAccount(ctx, acc) + } return nil }) } diff --git a/types/errors.go b/types/errors.go index 2290ff833e..f54a8fcc17 100644 --- a/types/errors.go +++ b/types/errors.go @@ -24,12 +24,13 @@ const ( CodeOK CodeType = 0 CodeInternal CodeType = 1 CodeTxParse CodeType = 2 - CodeBadNonce CodeType = 3 - CodeUnauthorized CodeType = 4 - CodeInsufficientFunds CodeType = 5 - CodeUnknownRequest CodeType = 6 - CodeUnrecognizedAddress CodeType = 7 - CodeInvalidSequence CodeType = 8 + CodeGenesisParse CodeType = 3 + CodeBadNonce CodeType = 4 + CodeUnauthorized CodeType = 5 + CodeInsufficientFunds CodeType = 6 + CodeUnknownRequest CodeType = 7 + CodeUnrecognizedAddress CodeType = 8 + CodeInvalidSequence CodeType = 9 ) // NOTE: Don't stringer this, we'll put better messages in later. @@ -39,6 +40,8 @@ func CodeToDefaultMsg(code CodeType) string { return "Internal error" case CodeTxParse: return "Tx parse error" + case CodeGenesisParse: + return "Genesis parse error" case CodeBadNonce: return "Bad nonce" case CodeUnauthorized: @@ -67,6 +70,9 @@ func ErrInternal(msg string) Error { func ErrTxParse(msg string) Error { return newError(CodeTxParse, msg) } +func ErrGenesisParse(msg string) Error { + return newError(CodeGenesisParse, msg) +} func ErrBadNonce(msg string) Error { return newError(CodeBadNonce, msg) } From 849139ebeb8143b726f9a1a87d999133aad8cfb4 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 8 Feb 2018 21:16:33 +0000 Subject: [PATCH 06/15] working --- baseapp/baseapp.go | 4 ++-- examples/basecoin/app/app.go | 20 +++++++++++++++----- examples/basecoin/app/init_baseapp.go | 8 ++++++-- examples/basecoin/app/testapp.go | 2 +- examples/basecoin/cmd/basecoind/main.go | 9 +++++---- types/genesis.go | 2 +- 6 files changed, 30 insertions(+), 15 deletions(-) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 80cd19eebe..2141d17ab2 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -36,7 +36,7 @@ type BaseApp struct { txDecoder sdk.TxDecoder // unmarshal rawjsonbytes to the initialize application - initStater sdk.InitStater + InitStater sdk.InitStater // TODO make unexposed once certain refactoring from basecoin -> baseapp // ante handler for fee and auth defaultAnteHandler sdk.AnteHandler @@ -107,7 +107,7 @@ func (app *BaseApp) SetTxDecoder(txDecoder sdk.TxDecoder) { app.txDecoder = txDecoder } func (app *BaseApp) SetInitStater(initStater sdk.InitStater) { - app.initStater = initStater + app.InitStater = initStater } func (app *BaseApp) SetDefaultAnteHandler(ah sdk.AnteHandler) { app.defaultAnteHandler = ah diff --git a/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index 19de9e9e35..29b6a950d8 100644 --- a/examples/basecoin/app/app.go +++ b/examples/basecoin/app/app.go @@ -6,6 +6,7 @@ import ( bam "github.com/cosmos/cosmos-sdk/baseapp" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/tendermint/abci/server" "github.com/tendermint/go-wire" cmn "github.com/tendermint/tmlibs/common" @@ -30,7 +31,8 @@ type BasecoinApp struct { // NewBasecoinApp - create new BasecoinApp // TODO: This should take in more configuration options. -func NewBasecoinApp() *BasecoinApp { +// TODO: This should be moved into +func NewBasecoinApp(genesisPath string) *BasecoinApp { // Create and configure app. var app = &BasecoinApp{} @@ -39,12 +41,20 @@ func NewBasecoinApp() *BasecoinApp { app.initStores() // ./init_stores.go app.initHandlers() // ./init_handlers.go - // TODO: Load genesis - // TODO: InitChain with validators - // TODO: Set the genesis accounts + genesisiDoc, err := bam.GenesisDocFromFile(genesisPath) + if err != nil { + panic(fmt.Errorf("error loading genesis state: %v", err)) + } + + // TODO: InitChain with validators from genesis transaction bytes + + // load application initial state + err = app.BaseApp.InitStater(genesisiDoc.AppState) + if err != nil { + panic(fmt.Errorf("error loading application genesis state: %v", err)) + } app.loadStores() - return app } diff --git a/examples/basecoin/app/init_baseapp.go b/examples/basecoin/app/init_baseapp.go index 7b3bb7bcaa..70afb406a9 100644 --- a/examples/basecoin/app/init_baseapp.go +++ b/examples/basecoin/app/init_baseapp.go @@ -34,7 +34,10 @@ func (app *BasecoinApp) initBaseAppTxDecoder() { // define the custom logic for basecoin initialization func (app *BasecoinApp) initBaseAppInitStater() { accountMapper := app.accountMapper - app.BaseApp.SetInitStater(func(ctx sdk.Context, stateJSON []byte) sdk.Error { + ctxCheckTx := app.BaseApp.NewContext(true, nil) + ctxDeliverTx := app.BaseApp.NewContext(false, nil) + + app.BaseApp.SetInitStater(func(stateJSON []byte) sdk.Error { var accs []*types.AppAccount @@ -44,7 +47,8 @@ func (app *BasecoinApp) initBaseAppInitStater() { } for _, acc := range accs { - accountMapper.SetAccount(ctx, acc) + accountMapper.SetAccount(ctxCheckTx, acc) + accountMapper.SetAccount(ctxDeliverTx, acc) } return nil }) diff --git a/examples/basecoin/app/testapp.go b/examples/basecoin/app/testapp.go index 544c48c0f7..8603911d51 100644 --- a/examples/basecoin/app/testapp.go +++ b/examples/basecoin/app/testapp.go @@ -10,7 +10,7 @@ type testBasecoinApp struct { } func newTestBasecoinApp() *testBasecoinApp { - app := NewBasecoinApp() + app := NewBasecoinApp("") tba := &testBasecoinApp{ BasecoinApp: app, } diff --git a/examples/basecoin/cmd/basecoind/main.go b/examples/basecoin/cmd/basecoind/main.go index cde9de191a..623bb35e45 100644 --- a/examples/basecoin/cmd/basecoind/main.go +++ b/examples/basecoin/cmd/basecoind/main.go @@ -1,9 +1,10 @@ package main -import ( - "fmt" -) +import "github.com/cosmos/cosmos-sdk/examples/basecoin/app" func main() { - fmt.Println("TODO: move examples/basecoin/main.go here and refactor") + // TODO CREATE CLI + + bapp := app.NewBasecoinApp("") + bapp.RunForever() } diff --git a/types/genesis.go b/types/genesis.go index 995d2de574..eaf72b8b74 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -1,4 +1,4 @@ package types // function variable used to initialize application state at genesis -type InitStater func(ctx Context, stateJSON []byte) Error +type InitStater func(stateJSON []byte) Error From 17acf9e18d2f76ab0a7a2cfe8eb57cf0061a69f8 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 9 Feb 2018 04:33:42 +0000 Subject: [PATCH 07/15] working --- baseapp/context.go | 5 +- baseapp/genesis.go | 71 +++++++++++++++++++++++++++ examples/basecoin/app/app.go | 26 +++++++++- examples/basecoin/app/init_baseapp.go | 4 +- types/genesis.go | 2 +- 5 files changed, 101 insertions(+), 7 deletions(-) create mode 100644 baseapp/genesis.go diff --git a/baseapp/context.go b/baseapp/context.go index 281220665b..e5a60f9674 100644 --- a/baseapp/context.go +++ b/baseapp/context.go @@ -1,6 +1,8 @@ package baseapp -import sdk "github.com/cosmos/cosmos-sdk/types" +import ( + sdk "github.com/cosmos/cosmos-sdk/types" +) // NewContext returns a new Context suitable for AnteHandler (and indirectly Handler) processing. // NOTE: txBytes may be nil to support TestApp.RunCheckTx @@ -12,6 +14,7 @@ func (app *BaseApp) NewContext(isCheckTx bool, txBytes []byte) sdk.Context { } else { store = app.msDeliver } + if store == nil { panic("BaseApp.NewContext() requires BeginBlock(): missing store") } diff --git a/baseapp/genesis.go b/baseapp/genesis.go new file mode 100644 index 0000000000..943f24bb8a --- /dev/null +++ b/baseapp/genesis.go @@ -0,0 +1,71 @@ +package baseapp + +import ( + "encoding/json" + "io/ioutil" + "time" + + crypto "github.com/tendermint/go-crypto" + cmn "github.com/tendermint/tmlibs/common" +) + +// TODO this is dup code from tendermint-core to avoid dep issues +// should probably remove from both SDK / Tendermint and move to tmlibs +// ^^^^^^^^^^^^^ This is my preference to avoid DEP hell +// or sync up versioning and just reference tendermint + +// GenesisDoc defines the initial conditions for a tendermint blockchain, in particular its validator set. +type GenesisDoc struct { + GenesisTime time.Time `json:"genesis_time"` + ChainID string `json:"chain_id"` + ConsensusParams *ConsensusParams `json:"consensus_params,omitempty"` + Validators []GenesisValidator `json:"validators"` + AppHash cmn.HexBytes `json:"app_hash"` + AppState json.RawMessage `json:"app_state,omitempty"` +} + +//nolint TODO remove +type ConsensusParams struct { + BlockSize `json:"block_size_params"` + TxSize `json:"tx_size_params"` + BlockGossip `json:"block_gossip_params"` + EvidenceParams `json:"evidence_params"` +} +type GenesisValidator struct { + PubKey crypto.PubKey `json:"pub_key"` + Power int64 `json:"power"` + Name string `json:"name"` +} +type BlockSize struct { + MaxBytes int `json:"max_bytes"` // NOTE: must not be 0 nor greater than 100MB + MaxTxs int `json:"max_txs"` + MaxGas int64 `json:"max_gas"` +} +type TxSize struct { + MaxBytes int `json:"max_bytes"` + MaxGas int64 `json:"max_gas"` +} +type BlockGossip struct { + BlockPartSizeBytes int `json:"block_part_size_bytes"` // NOTE: must not be 0 +} +type EvidenceParams struct { + MaxAge int64 `json:"max_age"` // only accept new evidence more recent than this +} + +// GenesisDocFromFile reads JSON data from a file and unmarshalls it into a GenesisDoc. +func GenesisDocFromFile(genDocFile string) (*GenesisDoc, error) { + if genDocFile == "" { + var g GenesisDoc + return &g, nil + } + jsonBlob, err := ioutil.ReadFile(genDocFile) + if err != nil { + return nil, err + } + genDoc := GenesisDoc{} + err = json.Unmarshal(jsonBlob, &genDoc) + if err != nil { + return nil, err + } + return &genDoc, nil +} diff --git a/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index 29b6a950d8..8fcc2bbe1c 100644 --- a/examples/basecoin/app/app.go +++ b/examples/basecoin/app/app.go @@ -8,6 +8,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/tendermint/abci/server" + abci "github.com/tendermint/abci/types" "github.com/tendermint/go-wire" cmn "github.com/tendermint/tmlibs/common" ) @@ -36,6 +37,7 @@ func NewBasecoinApp(genesisPath string) *BasecoinApp { // Create and configure app. var app = &BasecoinApp{} + app.initCapKeys() // ./init_capkeys.go app.initBaseApp() // ./init_baseapp.go app.initStores() // ./init_stores.go @@ -48,13 +50,33 @@ func NewBasecoinApp(genesisPath string) *BasecoinApp { // TODO: InitChain with validators from genesis transaction bytes - // load application initial state - err = app.BaseApp.InitStater(genesisiDoc.AppState) + // set first begin block + header := abci.Header{ + ChainID: "", + Height: 0, + Time: -1, // TODO + NumTxs: -1, // TODO + LastCommitHash: []byte{0x00}, + DataHash: nil, // TODO + ValidatorsHash: nil, // TODO + AppHash: nil, // TODO + } + app.BaseApp.BeginBlock(abci.RequestBeginBlock{ + Hash: nil, // TODO + Header: header, + AbsentValidators: nil, // TODO + ByzantineValidators: nil, // TODO + }) + + ctxCheckTx := app.BaseApp.NewContext(true, nil) + ctxDeliverTx := app.BaseApp.NewContext(false, nil) + err = app.BaseApp.InitStater(ctxCheckTx, ctxDeliverTx, genesisiDoc.AppState) if err != nil { panic(fmt.Errorf("error loading application genesis state: %v", err)) } app.loadStores() + return app } diff --git a/examples/basecoin/app/init_baseapp.go b/examples/basecoin/app/init_baseapp.go index 70afb406a9..525aa2f676 100644 --- a/examples/basecoin/app/init_baseapp.go +++ b/examples/basecoin/app/init_baseapp.go @@ -34,10 +34,8 @@ func (app *BasecoinApp) initBaseAppTxDecoder() { // define the custom logic for basecoin initialization func (app *BasecoinApp) initBaseAppInitStater() { accountMapper := app.accountMapper - ctxCheckTx := app.BaseApp.NewContext(true, nil) - ctxDeliverTx := app.BaseApp.NewContext(false, nil) - app.BaseApp.SetInitStater(func(stateJSON []byte) sdk.Error { + app.BaseApp.SetInitStater(func(ctxCheckTx, ctxDeliverTx sdk.Context, stateJSON []byte) sdk.Error { var accs []*types.AppAccount diff --git a/types/genesis.go b/types/genesis.go index eaf72b8b74..24c311feba 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -1,4 +1,4 @@ package types // function variable used to initialize application state at genesis -type InitStater func(stateJSON []byte) Error +type InitStater func(ctxCheckTx, ctxDeliverTx Context, stateJSON []byte) Error From 7206c434d442a12cea9a6d449231759bb8cb1b6e Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 9 Feb 2018 12:48:11 +0000 Subject: [PATCH 08/15] genesis exisiting tests pass --- examples/basecoin/app/init_baseapp.go | 7 +++++-- types/genesis.go | 4 +++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/examples/basecoin/app/init_baseapp.go b/examples/basecoin/app/init_baseapp.go index 525aa2f676..f0528f98c0 100644 --- a/examples/basecoin/app/init_baseapp.go +++ b/examples/basecoin/app/init_baseapp.go @@ -35,11 +35,14 @@ func (app *BasecoinApp) initBaseAppTxDecoder() { func (app *BasecoinApp) initBaseAppInitStater() { accountMapper := app.accountMapper - app.BaseApp.SetInitStater(func(ctxCheckTx, ctxDeliverTx sdk.Context, stateJSON []byte) sdk.Error { + app.BaseApp.SetInitStater(func(ctxCheckTx, ctxDeliverTx sdk.Context, state json.RawMessage) sdk.Error { + if state == nil { + return nil + } var accs []*types.AppAccount - err := json.Unmarshal(stateJSON, &accs) + err := json.Unmarshal(state, &accs) if err != nil { return sdk.ErrGenesisParse("").TraceCause(err, "") } diff --git a/types/genesis.go b/types/genesis.go index 24c311feba..008661f282 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -1,4 +1,6 @@ package types +import "encoding/json" + // function variable used to initialize application state at genesis -type InitStater func(ctxCheckTx, ctxDeliverTx Context, stateJSON []byte) Error +type InitStater func(ctxCheckTx, ctxDeliverTx Context, state json.RawMessage) Error From 2b9633db4ac53d99337bf828dd3e63dde0dd1000 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 9 Feb 2018 16:24:21 +0000 Subject: [PATCH 09/15] working genesis tests --- examples/basecoin/app/app_test.go | 15 ++++--- examples/basecoin/app/init_baseapp.go | 57 ++++++++++++++++++++++++--- 2 files changed, 62 insertions(+), 10 deletions(-) diff --git a/examples/basecoin/app/app_test.go b/examples/basecoin/app/app_test.go index 15b98bd4ca..8687d47dc4 100644 --- a/examples/basecoin/app/app_test.go +++ b/examples/basecoin/app/app_test.go @@ -57,11 +57,16 @@ func TestSendMsg(t *testing.T) { PubKey: pk, Sequence: 0, } - accs := []types.AppAccount{ - {baseAcc, "foobart"}, - {baseAcc, "endofzeworld"}, + accs := []*GenesisAccount{ + NewGenesisAccount(types.AppAccount{baseAcc, "foobart"}), + NewGenesisAccount(types.AppAccount{baseAcc, "endofzeworld"}), } bytes, err := json.MarshalIndent(&accs, "", "\t") - _ = bytes - // XXX test the json bytes in the InitStater + + app := tba.BasecoinApp + ctxCheckTx := app.BaseApp.NewContext(true, nil) + ctxDeliverTx := app.BaseApp.NewContext(false, nil) + err = app.BaseApp.InitStater(ctxCheckTx, ctxDeliverTx, bytes) + require.Nil(t, err) + } diff --git a/examples/basecoin/app/init_baseapp.go b/examples/basecoin/app/init_baseapp.go index f0528f98c0..14402ef4a6 100644 --- a/examples/basecoin/app/init_baseapp.go +++ b/examples/basecoin/app/init_baseapp.go @@ -6,6 +6,9 @@ import ( "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/examples/basecoin/types" sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/x/auth" + crypto "github.com/tendermint/go-crypto" + cmn "github.com/tendermint/tmlibs/common" ) // initCapKeys, initBaseApp, initStores, initHandlers. @@ -31,6 +34,44 @@ func (app *BasecoinApp) initBaseAppTxDecoder() { }) } +// We use GenesisAccount instead of types.AppAccount for cleaner json input of PubKey +type GenesisAccount struct { + Name string `json:"name"` + Address crypto.Address `json:"address"` + Coins sdk.Coins `json:"coins"` + PubKey cmn.HexBytes `json:"public_key"` + Sequence int64 `json:"sequence"` +} + +func NewGenesisAccount(aa types.AppAccount) *GenesisAccount { + return &GenesisAccount{ + Name: aa.Name, + Address: aa.Address, + Coins: aa.Coins, + PubKey: aa.PubKey.Bytes(), + Sequence: aa.Sequence, + } +} + +// convert GenesisAccount to AppAccount +func (ga *GenesisAccount) toAppAccount() (acc types.AppAccount, err error) { + + pk, err := crypto.PubKeyFromBytes(ga.PubKey) + if err != nil { + return + } + baseAcc := auth.BaseAccount{ + Address: ga.Address, + Coins: ga.Coins, + PubKey: pk, + Sequence: ga.Sequence, + } + return types.AppAccount{ + BaseAccount: baseAcc, + Name: "foobart", + }, nil +} + // define the custom logic for basecoin initialization func (app *BasecoinApp) initBaseAppInitStater() { accountMapper := app.accountMapper @@ -40,16 +81,22 @@ func (app *BasecoinApp) initBaseAppInitStater() { return nil } - var accs []*types.AppAccount + var gaccs []*GenesisAccount - err := json.Unmarshal(state, &accs) + err := json.Unmarshal(state, &gaccs) if err != nil { return sdk.ErrGenesisParse("").TraceCause(err, "") } - for _, acc := range accs { - accountMapper.SetAccount(ctxCheckTx, acc) - accountMapper.SetAccount(ctxDeliverTx, acc) + for _, gacc := range gaccs { + acc, err := gacc.toAppAccount() + if err != nil { + return sdk.ErrGenesisParse("").TraceCause(err, "") + } + + //panic(fmt.Sprintf("debug acc: %s\n", acc)) + accountMapper.SetAccount(ctxCheckTx, &acc.BaseAccount) + accountMapper.SetAccount(ctxDeliverTx, &acc.BaseAccount) } return nil }) From fd1684ab6bfbe7e761cf81e14c8e990880e990fc Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 9 Feb 2018 16:56:23 +0000 Subject: [PATCH 10/15] ... --- examples/basecoin/app/app.go | 30 +++++++++++++++------------ examples/basecoin/app/app_test.go | 11 ++++++---- examples/basecoin/app/init_baseapp.go | 6 ++---- 3 files changed, 26 insertions(+), 21 deletions(-) diff --git a/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index 8fcc2bbe1c..312cda9a78 100644 --- a/examples/basecoin/app/app.go +++ b/examples/basecoin/app/app.go @@ -32,15 +32,18 @@ type BasecoinApp struct { // NewBasecoinApp - create new BasecoinApp // TODO: This should take in more configuration options. -// TODO: This should be moved into +// TODO: This should be moved into baseapp to isolate complexity func NewBasecoinApp(genesisPath string) *BasecoinApp { // Create and configure app. var app = &BasecoinApp{} - app.initCapKeys() // ./init_capkeys.go - app.initBaseApp() // ./init_baseapp.go - app.initStores() // ./init_stores.go + // TODO open up out of functions, or introduce clarity, + // interdependancies are a nightmare to debug + app.initCapKeys() // ./init_capkeys.go + app.initBaseApp() // ./init_baseapp.go + app.initStores() // ./init_stores.go + app.initBaseAppInitStater() app.initHandlers() // ./init_handlers.go genesisiDoc, err := bam.GenesisDocFromFile(genesisPath) @@ -50,26 +53,27 @@ func NewBasecoinApp(genesisPath string) *BasecoinApp { // TODO: InitChain with validators from genesis transaction bytes - // set first begin block + // very first begin block used for context when setting genesis accounts header := abci.Header{ ChainID: "", Height: 0, - Time: -1, // TODO - NumTxs: -1, // TODO + Time: -1, + NumTxs: -1, LastCommitHash: []byte{0x00}, - DataHash: nil, // TODO - ValidatorsHash: nil, // TODO - AppHash: nil, // TODO + DataHash: nil, + ValidatorsHash: nil, + AppHash: nil, } app.BaseApp.BeginBlock(abci.RequestBeginBlock{ - Hash: nil, // TODO + Hash: nil, Header: header, - AbsentValidators: nil, // TODO - ByzantineValidators: nil, // TODO + AbsentValidators: nil, + ByzantineValidators: nil, }) ctxCheckTx := app.BaseApp.NewContext(true, nil) ctxDeliverTx := app.BaseApp.NewContext(false, nil) + err = app.BaseApp.InitStater(ctxCheckTx, ctxDeliverTx, genesisiDoc.AppState) if err != nil { panic(fmt.Errorf("error loading application genesis state: %v", err)) diff --git a/examples/basecoin/app/app_test.go b/examples/basecoin/app/app_test.go index 8687d47dc4..9178820126 100644 --- a/examples/basecoin/app/app_test.go +++ b/examples/basecoin/app/app_test.go @@ -57,11 +57,12 @@ func TestSendMsg(t *testing.T) { PubKey: pk, Sequence: 0, } - accs := []*GenesisAccount{ - NewGenesisAccount(types.AppAccount{baseAcc, "foobart"}), - NewGenesisAccount(types.AppAccount{baseAcc, "endofzeworld"}), + acc := types.AppAccount{baseAcc, "foobart"} + + gaccs := []*GenesisAccount{ + NewGenesisAccount(acc), } - bytes, err := json.MarshalIndent(&accs, "", "\t") + bytes, err := json.MarshalIndent(&gaccs, "", "\t") app := tba.BasecoinApp ctxCheckTx := app.BaseApp.NewContext(true, nil) @@ -69,4 +70,6 @@ func TestSendMsg(t *testing.T) { err = app.BaseApp.InitStater(ctxCheckTx, ctxDeliverTx, bytes) require.Nil(t, err) + res1 := app.accountMapper.GetAccount(ctxDeliverTx, baseAcc.Address) + assert.Equal(t, baseAcc, res1) } diff --git a/examples/basecoin/app/init_baseapp.go b/examples/basecoin/app/init_baseapp.go index 14402ef4a6..34272e6bb5 100644 --- a/examples/basecoin/app/init_baseapp.go +++ b/examples/basecoin/app/init_baseapp.go @@ -93,10 +93,8 @@ func (app *BasecoinApp) initBaseAppInitStater() { if err != nil { return sdk.ErrGenesisParse("").TraceCause(err, "") } - - //panic(fmt.Sprintf("debug acc: %s\n", acc)) - accountMapper.SetAccount(ctxCheckTx, &acc.BaseAccount) - accountMapper.SetAccount(ctxDeliverTx, &acc.BaseAccount) + accountMapper.SetAccount(ctxCheckTx, acc.BaseAccount) + accountMapper.SetAccount(ctxDeliverTx, acc.BaseAccount) } return nil }) From b09653c9ea29071c5c9035faa026ad58796ed47c Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Fri, 9 Feb 2018 18:04:18 +0100 Subject: [PATCH 11/15] Fix init state bug --- examples/basecoin/app/app_test.go | 4 ++-- examples/basecoin/app/init_baseapp.go | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/basecoin/app/app_test.go b/examples/basecoin/app/app_test.go index 9178820126..9749f4e3cf 100644 --- a/examples/basecoin/app/app_test.go +++ b/examples/basecoin/app/app_test.go @@ -57,7 +57,7 @@ func TestSendMsg(t *testing.T) { PubKey: pk, Sequence: 0, } - acc := types.AppAccount{baseAcc, "foobart"} + acc := &types.AppAccount{baseAcc, "foobart"} gaccs := []*GenesisAccount{ NewGenesisAccount(acc), @@ -71,5 +71,5 @@ func TestSendMsg(t *testing.T) { require.Nil(t, err) res1 := app.accountMapper.GetAccount(ctxDeliverTx, baseAcc.Address) - assert.Equal(t, baseAcc, res1) + assert.Equal(t, acc, res1) } diff --git a/examples/basecoin/app/init_baseapp.go b/examples/basecoin/app/init_baseapp.go index 34272e6bb5..e1735d3ed2 100644 --- a/examples/basecoin/app/init_baseapp.go +++ b/examples/basecoin/app/init_baseapp.go @@ -43,7 +43,7 @@ type GenesisAccount struct { Sequence int64 `json:"sequence"` } -func NewGenesisAccount(aa types.AppAccount) *GenesisAccount { +func NewGenesisAccount(aa *types.AppAccount) *GenesisAccount { return &GenesisAccount{ Name: aa.Name, Address: aa.Address, @@ -54,7 +54,7 @@ func NewGenesisAccount(aa types.AppAccount) *GenesisAccount { } // convert GenesisAccount to AppAccount -func (ga *GenesisAccount) toAppAccount() (acc types.AppAccount, err error) { +func (ga *GenesisAccount) toAppAccount() (acc *types.AppAccount, err error) { pk, err := crypto.PubKeyFromBytes(ga.PubKey) if err != nil { @@ -66,7 +66,7 @@ func (ga *GenesisAccount) toAppAccount() (acc types.AppAccount, err error) { PubKey: pk, Sequence: ga.Sequence, } - return types.AppAccount{ + return &types.AppAccount{ BaseAccount: baseAcc, Name: "foobart", }, nil @@ -93,8 +93,8 @@ func (app *BasecoinApp) initBaseAppInitStater() { if err != nil { return sdk.ErrGenesisParse("").TraceCause(err, "") } - accountMapper.SetAccount(ctxCheckTx, acc.BaseAccount) - accountMapper.SetAccount(ctxDeliverTx, acc.BaseAccount) + accountMapper.SetAccount(ctxCheckTx, acc) + accountMapper.SetAccount(ctxDeliverTx, acc) } return nil }) From 0bab936d701a1dd8f2a544a271b452f437158eef Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Fri, 9 Feb 2018 17:07:54 +0000 Subject: [PATCH 12/15] initgen tests complete --- examples/basecoin/app/init_baseapp.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/basecoin/app/init_baseapp.go b/examples/basecoin/app/init_baseapp.go index e1735d3ed2..7d3a898354 100644 --- a/examples/basecoin/app/init_baseapp.go +++ b/examples/basecoin/app/init_baseapp.go @@ -68,7 +68,7 @@ func (ga *GenesisAccount) toAppAccount() (acc *types.AppAccount, err error) { } return &types.AppAccount{ BaseAccount: baseAcc, - Name: "foobart", + Name: ga.Name, }, nil } From ed662566eb487aafa40f488eab9aa2eb02bd7b63 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Mon, 12 Feb 2018 12:55:22 +0000 Subject: [PATCH 13/15] remove genesis of checkTx --- examples/basecoin/app/app.go | 5 ++--- examples/basecoin/app/app_test.go | 7 +++---- examples/basecoin/app/init_baseapp.go | 5 ++--- types/genesis.go | 2 +- 4 files changed, 8 insertions(+), 11 deletions(-) diff --git a/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index 312cda9a78..7abc3f5b7d 100644 --- a/examples/basecoin/app/app.go +++ b/examples/basecoin/app/app.go @@ -71,10 +71,9 @@ func NewBasecoinApp(genesisPath string) *BasecoinApp { ByzantineValidators: nil, }) - ctxCheckTx := app.BaseApp.NewContext(true, nil) - ctxDeliverTx := app.BaseApp.NewContext(false, nil) + ctx := app.BaseApp.NewContext(false, nil) // context for DeliverTx - err = app.BaseApp.InitStater(ctxCheckTx, ctxDeliverTx, genesisiDoc.AppState) + err = app.BaseApp.InitStater(ctx, genesisiDoc.AppState) if err != nil { panic(fmt.Errorf("error loading application genesis state: %v", err)) } diff --git a/examples/basecoin/app/app_test.go b/examples/basecoin/app/app_test.go index 9749f4e3cf..edc4deeef2 100644 --- a/examples/basecoin/app/app_test.go +++ b/examples/basecoin/app/app_test.go @@ -65,11 +65,10 @@ func TestSendMsg(t *testing.T) { bytes, err := json.MarshalIndent(&gaccs, "", "\t") app := tba.BasecoinApp - ctxCheckTx := app.BaseApp.NewContext(true, nil) - ctxDeliverTx := app.BaseApp.NewContext(false, nil) - err = app.BaseApp.InitStater(ctxCheckTx, ctxDeliverTx, bytes) + ctx := app.BaseApp.NewContext(false, nil) // context for DeliverTx + err = app.BaseApp.InitStater(ctx, bytes) require.Nil(t, err) - res1 := app.accountMapper.GetAccount(ctxDeliverTx, baseAcc.Address) + res1 := app.accountMapper.GetAccount(ctx, baseAcc.Address) assert.Equal(t, acc, res1) } diff --git a/examples/basecoin/app/init_baseapp.go b/examples/basecoin/app/init_baseapp.go index 7d3a898354..aac14e4a52 100644 --- a/examples/basecoin/app/init_baseapp.go +++ b/examples/basecoin/app/init_baseapp.go @@ -76,7 +76,7 @@ func (ga *GenesisAccount) toAppAccount() (acc *types.AppAccount, err error) { func (app *BasecoinApp) initBaseAppInitStater() { accountMapper := app.accountMapper - app.BaseApp.SetInitStater(func(ctxCheckTx, ctxDeliverTx sdk.Context, state json.RawMessage) sdk.Error { + app.BaseApp.SetInitStater(func(ctx sdk.Context, state json.RawMessage) sdk.Error { if state == nil { return nil } @@ -93,8 +93,7 @@ func (app *BasecoinApp) initBaseAppInitStater() { if err != nil { return sdk.ErrGenesisParse("").TraceCause(err, "") } - accountMapper.SetAccount(ctxCheckTx, acc) - accountMapper.SetAccount(ctxDeliverTx, acc) + accountMapper.SetAccount(ctx, acc) } return nil }) diff --git a/types/genesis.go b/types/genesis.go index 008661f282..643235e3e9 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -3,4 +3,4 @@ package types import "encoding/json" // function variable used to initialize application state at genesis -type InitStater func(ctxCheckTx, ctxDeliverTx Context, state json.RawMessage) Error +type InitStater func(ctx Context, state json.RawMessage) Error From 658d7633a3164256383d420aa42be4864c9d138c Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 13 Feb 2018 10:28:24 +0000 Subject: [PATCH 14/15] cleanup --- examples/basecoin/app/app.go | 20 ++------------------ 1 file changed, 2 insertions(+), 18 deletions(-) diff --git a/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index 7abc3f5b7d..daba43f898 100644 --- a/examples/basecoin/app/app.go +++ b/examples/basecoin/app/app.go @@ -53,24 +53,8 @@ func NewBasecoinApp(genesisPath string) *BasecoinApp { // TODO: InitChain with validators from genesis transaction bytes - // very first begin block used for context when setting genesis accounts - header := abci.Header{ - ChainID: "", - Height: 0, - Time: -1, - NumTxs: -1, - LastCommitHash: []byte{0x00}, - DataHash: nil, - ValidatorsHash: nil, - AppHash: nil, - } - app.BaseApp.BeginBlock(abci.RequestBeginBlock{ - Hash: nil, - Header: header, - AbsentValidators: nil, - ByzantineValidators: nil, - }) - + // set up the cache store for ctx, get ctx + app.BaseApp.BeginBlock(abci.RequestBeginBlock{Header: abci.Header{}}) ctx := app.BaseApp.NewContext(false, nil) // context for DeliverTx err = app.BaseApp.InitStater(ctx, genesisiDoc.AppState) From d9ebe34c3225dfb8cae24ff6824cf32acf4efacb Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 13 Feb 2018 07:30:51 -0500 Subject: [PATCH 15/15] fixes from review --- baseapp/baseapp.go | 6 +- baseapp/genesis.go | 45 +-------------- examples/basecoin/app/app.go | 6 +- examples/basecoin/app/app_test.go | 14 ++--- examples/basecoin/app/init_baseapp.go | 79 ++++++++++++--------------- types/errors.go | 15 ++--- 6 files changed, 61 insertions(+), 104 deletions(-) diff --git a/baseapp/baseapp.go b/baseapp/baseapp.go index 2141d17ab2..e92f58bdcc 100644 --- a/baseapp/baseapp.go +++ b/baseapp/baseapp.go @@ -35,8 +35,9 @@ type BaseApp struct { // unmarshal []byte into sdk.Tx txDecoder sdk.TxDecoder - // unmarshal rawjsonbytes to the initialize application - InitStater sdk.InitStater // TODO make unexposed once certain refactoring from basecoin -> baseapp + // unmarshal rawjsonbytes to initialize the application + // TODO unexpose and call from InitChain + InitStater sdk.InitStater // ante handler for fee and auth defaultAnteHandler sdk.AnteHandler @@ -204,6 +205,7 @@ func (app *BaseApp) SetOption(req abci.RequestSetOption) (res abci.ResponseSetOp // Implements ABCI func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitChain) { // TODO: Use req.Validators + // TODO: Use req.AppStateJSON (?) return } diff --git a/baseapp/genesis.go b/baseapp/genesis.go index 943f24bb8a..b2dad3e334 100644 --- a/baseapp/genesis.go +++ b/baseapp/genesis.go @@ -3,53 +3,14 @@ package baseapp import ( "encoding/json" "io/ioutil" - "time" - - crypto "github.com/tendermint/go-crypto" - cmn "github.com/tendermint/tmlibs/common" ) -// TODO this is dup code from tendermint-core to avoid dep issues -// should probably remove from both SDK / Tendermint and move to tmlibs -// ^^^^^^^^^^^^^ This is my preference to avoid DEP hell -// or sync up versioning and just reference tendermint +// TODO: remove from here and pass the AppState +// through InitChain // GenesisDoc defines the initial conditions for a tendermint blockchain, in particular its validator set. type GenesisDoc struct { - GenesisTime time.Time `json:"genesis_time"` - ChainID string `json:"chain_id"` - ConsensusParams *ConsensusParams `json:"consensus_params,omitempty"` - Validators []GenesisValidator `json:"validators"` - AppHash cmn.HexBytes `json:"app_hash"` - AppState json.RawMessage `json:"app_state,omitempty"` -} - -//nolint TODO remove -type ConsensusParams struct { - BlockSize `json:"block_size_params"` - TxSize `json:"tx_size_params"` - BlockGossip `json:"block_gossip_params"` - EvidenceParams `json:"evidence_params"` -} -type GenesisValidator struct { - PubKey crypto.PubKey `json:"pub_key"` - Power int64 `json:"power"` - Name string `json:"name"` -} -type BlockSize struct { - MaxBytes int `json:"max_bytes"` // NOTE: must not be 0 nor greater than 100MB - MaxTxs int `json:"max_txs"` - MaxGas int64 `json:"max_gas"` -} -type TxSize struct { - MaxBytes int `json:"max_bytes"` - MaxGas int64 `json:"max_gas"` -} -type BlockGossip struct { - BlockPartSizeBytes int `json:"block_part_size_bytes"` // NOTE: must not be 0 -} -type EvidenceParams struct { - MaxAge int64 `json:"max_age"` // only accept new evidence more recent than this + AppState json.RawMessage `json:"app_state,omitempty"` } // GenesisDocFromFile reads JSON data from a file and unmarshalls it into a GenesisDoc. diff --git a/examples/basecoin/app/app.go b/examples/basecoin/app/app.go index daba43f898..4f26d49445 100644 --- a/examples/basecoin/app/app.go +++ b/examples/basecoin/app/app.go @@ -51,15 +51,15 @@ func NewBasecoinApp(genesisPath string) *BasecoinApp { panic(fmt.Errorf("error loading genesis state: %v", err)) } - // TODO: InitChain with validators from genesis transaction bytes - // set up the cache store for ctx, get ctx + // TODO: can InitChain handle this too ? app.BaseApp.BeginBlock(abci.RequestBeginBlock{Header: abci.Header{}}) ctx := app.BaseApp.NewContext(false, nil) // context for DeliverTx + // TODO: combine with InitChain and let tendermint invoke it. err = app.BaseApp.InitStater(ctx, genesisiDoc.AppState) if err != nil { - panic(fmt.Errorf("error loading application genesis state: %v", err)) + panic(fmt.Errorf("error initializing application genesis state: %v", err)) } app.loadStores() diff --git a/examples/basecoin/app/app_test.go b/examples/basecoin/app/app_test.go index edc4deeef2..ce071eeeda 100644 --- a/examples/basecoin/app/app_test.go +++ b/examples/basecoin/app/app_test.go @@ -52,17 +52,17 @@ func TestSendMsg(t *testing.T) { coins, err := sdk.ParseCoins("77foocoin,99barcoin") require.Nil(t, err) baseAcc := auth.BaseAccount{ - Address: addr, - Coins: coins, - PubKey: pk, - Sequence: 0, + Address: addr, + Coins: coins, } acc := &types.AppAccount{baseAcc, "foobart"} - gaccs := []*GenesisAccount{ - NewGenesisAccount(acc), + genesisState := GenesisState{ + Accounts: []*GenesisAccount{ + NewGenesisAccount(acc), + }, } - bytes, err := json.MarshalIndent(&gaccs, "", "\t") + bytes, err := json.MarshalIndent(genesisState, "", "\t") app := tba.BasecoinApp ctx := app.BaseApp.NewContext(false, nil) // context for DeliverTx diff --git a/examples/basecoin/app/init_baseapp.go b/examples/basecoin/app/init_baseapp.go index aac14e4a52..c1fcb94c6b 100644 --- a/examples/basecoin/app/init_baseapp.go +++ b/examples/basecoin/app/init_baseapp.go @@ -8,7 +8,6 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/x/auth" crypto "github.com/tendermint/go-crypto" - cmn "github.com/tendermint/tmlibs/common" ) // initCapKeys, initBaseApp, initStores, initHandlers. @@ -34,44 +33,6 @@ func (app *BasecoinApp) initBaseAppTxDecoder() { }) } -// We use GenesisAccount instead of types.AppAccount for cleaner json input of PubKey -type GenesisAccount struct { - Name string `json:"name"` - Address crypto.Address `json:"address"` - Coins sdk.Coins `json:"coins"` - PubKey cmn.HexBytes `json:"public_key"` - Sequence int64 `json:"sequence"` -} - -func NewGenesisAccount(aa *types.AppAccount) *GenesisAccount { - return &GenesisAccount{ - Name: aa.Name, - Address: aa.Address, - Coins: aa.Coins, - PubKey: aa.PubKey.Bytes(), - Sequence: aa.Sequence, - } -} - -// convert GenesisAccount to AppAccount -func (ga *GenesisAccount) toAppAccount() (acc *types.AppAccount, err error) { - - pk, err := crypto.PubKeyFromBytes(ga.PubKey) - if err != nil { - return - } - baseAcc := auth.BaseAccount{ - Address: ga.Address, - Coins: ga.Coins, - PubKey: pk, - Sequence: ga.Sequence, - } - return &types.AppAccount{ - BaseAccount: baseAcc, - Name: ga.Name, - }, nil -} - // define the custom logic for basecoin initialization func (app *BasecoinApp) initBaseAppInitStater() { accountMapper := app.accountMapper @@ -81,14 +42,13 @@ func (app *BasecoinApp) initBaseAppInitStater() { return nil } - var gaccs []*GenesisAccount - - err := json.Unmarshal(state, &gaccs) + genesisState := new(GenesisState) + err := json.Unmarshal(state, genesisState) if err != nil { return sdk.ErrGenesisParse("").TraceCause(err, "") } - for _, gacc := range gaccs { + for _, gacc := range genesisState.Accounts { acc, err := gacc.toAppAccount() if err != nil { return sdk.ErrGenesisParse("").TraceCause(err, "") @@ -98,3 +58,36 @@ func (app *BasecoinApp) initBaseAppInitStater() { return nil }) } + +//----------------------------------------------------- + +type GenesisState struct { + Accounts []*GenesisAccount `accounts` +} + +// GenesisAccount doesn't need pubkey or sequence +type GenesisAccount struct { + Name string `json:"name"` + Address crypto.Address `json:"address"` + Coins sdk.Coins `json:"coins"` +} + +func NewGenesisAccount(aa *types.AppAccount) *GenesisAccount { + return &GenesisAccount{ + Name: aa.Name, + Address: aa.Address, + Coins: aa.Coins, + } +} + +// convert GenesisAccount to AppAccount +func (ga *GenesisAccount) toAppAccount() (acc *types.AppAccount, err error) { + baseAcc := auth.BaseAccount{ + Address: ga.Address, + Coins: ga.Coins, + } + return &types.AppAccount{ + BaseAccount: baseAcc, + Name: ga.Name, + }, nil +} diff --git a/types/errors.go b/types/errors.go index f54a8fcc17..77cea98ac7 100644 --- a/types/errors.go +++ b/types/errors.go @@ -24,13 +24,14 @@ const ( CodeOK CodeType = 0 CodeInternal CodeType = 1 CodeTxParse CodeType = 2 - CodeGenesisParse CodeType = 3 - CodeBadNonce CodeType = 4 - CodeUnauthorized CodeType = 5 - CodeInsufficientFunds CodeType = 6 - CodeUnknownRequest CodeType = 7 - CodeUnrecognizedAddress CodeType = 8 - CodeInvalidSequence CodeType = 9 + CodeBadNonce CodeType = 3 + CodeUnauthorized CodeType = 4 + CodeInsufficientFunds CodeType = 5 + CodeUnknownRequest CodeType = 6 + CodeUnrecognizedAddress CodeType = 7 + CodeInvalidSequence CodeType = 8 + + CodeGenesisParse CodeType = 0xdead // TODO: remove ? ) // NOTE: Don't stringer this, we'll put better messages in later.