cosmos-sdk/baseapp/baseapp.go

389 lines
10 KiB
Go
Raw Normal View History

package baseapp
import (
2017-12-01 09:10:17 -08:00
"fmt"
2018-01-26 04:19:33 -08:00
"runtime/debug"
2017-12-01 09:10:17 -08:00
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
2018-02-14 08:16:06 -08:00
abci "github.com/tendermint/abci/types"
2017-12-26 17:04:48 -08:00
cmn "github.com/tendermint/tmlibs/common"
dbm "github.com/tendermint/tmlibs/db"
2017-12-01 09:10:17 -08:00
"github.com/tendermint/tmlibs/log"
"github.com/cosmos/cosmos-sdk/store"
2018-01-12 13:59:19 -08:00
sdk "github.com/cosmos/cosmos-sdk/types"
)
2017-12-26 17:04:48 -08:00
var mainHeaderKey = []byte("header")
2017-12-01 09:10:17 -08:00
2018-02-04 12:20:49 -08:00
// The ABCI application
type BaseApp struct {
// initialized on creation
logger log.Logger
name string // application name from abci.Info
db dbm.DB // common DB backend
cms sdk.CommitMultiStore // Main (uncached) state
router Router // handle any kind of message
2018-02-17 16:24:40 -08:00
// must be set
txDecoder sdk.TxDecoder // unmarshal []byte into sdk.Tx
anteHandler sdk.AnteHandler // ante handler for fee and auth
// may be nil
initChainer sdk.InitChainer // initialize state with validators and state blob
beginBlocker sdk.BeginBlocker // logic to run before any txs
endBlocker sdk.EndBlocker // logic to run after all txs, and to determine valset changes
//--------------------
// Volatile
// .msCheck and .ctxCheck are set on initialization and reset on Commit.
// .msDeliver and .ctxDeliver are (re-)set on BeginBlock.
// .valUpdates accumulate in DeliverTx and reset in BeginBlock.
// QUESTION: should we put valUpdates in the ctxDeliver?
2018-02-14 17:09:00 -08:00
msCheck sdk.CacheMultiStore // CheckTx state, a cache-wrap of `.cms`
msDeliver sdk.CacheMultiStore // DeliverTx state, a cache-wrap of `.cms`
ctxCheck sdk.Context // CheckTx context
ctxDeliver sdk.Context // DeliverTx context
2018-02-14 17:09:00 -08:00
valUpdates []abci.Validator // cached validator changes from DeliverTx
}
var _ abci.Application = &BaseApp{}
2018-02-04 12:20:49 -08:00
// Create and name new BaseApp
func NewBaseApp(name string, logger log.Logger, db dbm.DB) *BaseApp {
return &BaseApp{
logger: logger,
name: name,
db: db,
cms: store.NewCommitMultiStore(db),
router: NewRouter(),
2017-12-01 09:10:17 -08:00
}
2017-12-19 21:04:40 -08:00
}
2018-02-04 12:20:49 -08:00
// BaseApp Name
func (app *BaseApp) Name() string {
2017-12-21 23:30:44 -08:00
return app.name
}
2018-02-14 17:09:00 -08:00
// Mount a store to the provided key in the BaseApp multistore
func (app *BaseApp) MountStoresIAVL(keys ...*sdk.KVStoreKey) {
for _, key := range keys {
app.MountStore(key, sdk.StoreTypeIAVL)
}
}
2018-02-04 12:20:49 -08:00
// Mount a store to the provided key in the BaseApp multistore
func (app *BaseApp) MountStore(key sdk.StoreKey, typ sdk.StoreType) {
2018-01-26 04:19:33 -08:00
app.cms.MountStoreWithDB(key, typ, app.db)
2018-01-24 11:47:51 -08:00
}
2018-02-14 11:14:22 -08:00
// nolint - Set functions
func (app *BaseApp) SetTxDecoder(txDecoder sdk.TxDecoder) {
app.txDecoder = txDecoder
2017-12-19 21:04:40 -08:00
}
func (app *BaseApp) SetInitChainer(initChainer sdk.InitChainer) {
app.initChainer = initChainer
}
2018-02-14 17:09:00 -08:00
func (app *BaseApp) SetAnteHandler(ah sdk.AnteHandler) {
2018-02-14 11:14:22 -08:00
// deducts fee from payer, verifies signatures and nonces, sets Signers to ctx.
2018-02-14 17:09:00 -08:00
app.anteHandler = ah
2018-01-03 17:20:21 -08:00
}
2018-02-14 11:14:22 -08:00
// nolint - Get functions
2018-02-14 17:09:00 -08:00
func (app *BaseApp) Router() Router { return app.router }
2017-12-01 09:10:17 -08:00
/* TODO consider:
func (app *BaseApp) SetBeginBlocker(...) {}
func (app *BaseApp) SetEndBlocker(...) {}
*/
2018-02-14 08:16:06 -08:00
// load latest application version
func (app *BaseApp) LoadLatestVersion(mainKey sdk.StoreKey) error {
2018-01-26 04:19:33 -08:00
app.cms.LoadLatestVersion()
2018-01-12 13:59:19 -08:00
return app.initFromStore(mainKey)
2017-12-19 21:04:40 -08:00
}
2018-02-14 08:16:06 -08:00
// load application version
func (app *BaseApp) LoadVersion(version int64, mainKey sdk.StoreKey) error {
2018-01-26 04:19:33 -08:00
app.cms.LoadVersion(version)
2018-01-12 13:59:19 -08:00
return app.initFromStore(mainKey)
2017-12-20 17:34:51 -08:00
}
2018-02-14 08:16:06 -08:00
// the last CommitID of the multistore
func (app *BaseApp) LastCommitID() sdk.CommitID {
2018-01-26 04:19:33 -08:00
return app.cms.LastCommitID()
2017-12-26 17:04:48 -08:00
}
2018-02-14 08:16:06 -08:00
// the last commited block height
func (app *BaseApp) LastBlockHeight() int64 {
2018-01-26 04:19:33 -08:00
return app.cms.LastCommitID().Version
2017-12-26 17:04:48 -08:00
}
2018-02-14 08:16:06 -08:00
// initializes the remaining logic from app.cms
func (app *BaseApp) initFromStore(mainKey sdk.StoreKey) error {
2018-01-26 04:19:33 -08:00
var lastCommitID = app.cms.LastCommitID()
var main = app.cms.GetKVStore(mainKey)
2018-02-17 13:19:34 -08:00
var header abci.Header
2017-12-01 09:10:17 -08:00
2018-02-14 08:16:06 -08:00
// main store should exist.
2018-01-12 13:59:19 -08:00
if main == nil {
return errors.New("BaseApp expects MultiStore with 'main' KVStore")
2017-12-19 21:04:40 -08:00
}
2018-02-14 08:16:06 -08:00
// if we've committed before, we expect main://<mainHeaderKey>
2017-12-01 09:10:17 -08:00
if !lastCommitID.IsZero() {
2017-12-21 23:30:44 -08:00
headerBytes := main.Get(mainHeaderKey)
if len(headerBytes) == 0 {
errStr := fmt.Sprintf("Version > 0 but missing key %s", mainHeaderKey)
2017-12-19 21:04:40 -08:00
return errors.New(errStr)
2017-12-01 09:10:17 -08:00
}
2018-02-17 13:19:34 -08:00
err := proto.Unmarshal(headerBytes, &header)
2017-12-01 09:10:17 -08:00
if err != nil {
2017-12-19 21:04:40 -08:00
return errors.Wrap(err, "Failed to parse Header")
2017-12-01 09:10:17 -08:00
}
2017-12-21 23:30:44 -08:00
lastVersion := lastCommitID.Version
if header.Height != lastVersion {
errStr := fmt.Sprintf("Expected main://%s.Height %v but got %v", mainHeaderKey, lastVersion, header.Height)
2017-12-19 21:04:40 -08:00
return errors.New(errStr)
2017-12-01 09:10:17 -08:00
}
}
2017-12-20 17:34:51 -08:00
// initialize Check state
2018-02-17 13:19:34 -08:00
app.msCheck = app.cms.CacheMultiStore()
app.ctxCheck = app.NewContext(true, abci.Header{})
2017-12-20 17:34:51 -08:00
return nil
2017-12-01 09:10:17 -08:00
}
// NewContext returns a new Context with the correct store, the given header, and nil txBytes.
func (app *BaseApp) NewContext(isCheckTx bool, header abci.Header) sdk.Context {
if isCheckTx {
return sdk.NewContext(app.msCheck, header, true, nil)
}
return sdk.NewContext(app.msDeliver, header, false, nil)
}
2017-12-01 09:10:17 -08:00
//----------------------------------------
2018-02-14 08:16:06 -08:00
// ABCI
2017-12-01 09:10:17 -08:00
2018-02-04 12:20:49 -08:00
// Implements ABCI
func (app *BaseApp) Info(req abci.RequestInfo) abci.ResponseInfo {
2018-01-26 04:19:33 -08:00
lastCommitID := app.cms.LastCommitID()
2017-12-21 20:19:44 -08:00
return abci.ResponseInfo{
2017-12-21 23:30:44 -08:00
Data: app.name,
2017-12-21 20:19:44 -08:00
LastBlockHeight: lastCommitID.Version,
LastBlockAppHash: lastCommitID.Hash,
}
2017-12-21 20:19:44 -08:00
}
2018-02-04 12:20:49 -08:00
// Implements ABCI
func (app *BaseApp) SetOption(req abci.RequestSetOption) (res abci.ResponseSetOption) {
2017-12-21 23:30:44 -08:00
// TODO: Implement
return
2017-12-21 20:19:44 -08:00
}
2018-02-04 12:20:49 -08:00
// Implements ABCI
2018-02-16 17:58:51 -08:00
// InitChain runs the initialization logic directly on the CommitMultiStore and commits it.
func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitChain) {
if app.initChainer == nil {
// TODO: should we have some default handling of validators?
2018-02-15 06:35:46 -08:00
return
}
2018-02-16 17:58:51 -08:00
// make a context for the initialization.
// NOTE: we're writing to the cms directly, without a CacheWrap
ctx := sdk.NewContext(app.cms, abci.Header{}, false, nil)
2018-02-14 17:09:00 -08:00
res = app.initChainer(ctx, req)
// TODO: handle error https://github.com/cosmos/cosmos-sdk/issues/468
2018-02-16 17:58:51 -08:00
// XXX this commits everything and bumps the version.
2018-02-17 13:19:34 -08:00
// https://github.com/cosmos/cosmos-sdk/issues/442#issuecomment-366470148
2018-02-16 17:58:51 -08:00
app.cms.Commit()
2017-12-21 23:30:44 -08:00
return
2017-12-21 20:19:44 -08:00
}
2018-01-24 11:47:51 -08:00
// Implements ABCI.
2018-01-30 11:01:25 -08:00
// Delegates to CommitMultiStore if it implements Queryable
func (app *BaseApp) Query(req abci.RequestQuery) (res abci.ResponseQuery) {
2018-02-06 14:18:22 -08:00
queryable, ok := app.cms.(sdk.Queryable)
2018-01-30 11:01:25 -08:00
if !ok {
msg := "application doesn't support queries"
return sdk.ErrUnknownRequest(msg).Result().ToQuery()
}
2018-02-06 14:18:22 -08:00
return queryable.Query(req)
2017-12-21 20:19:44 -08:00
}
2018-02-04 12:20:49 -08:00
// Implements ABCI
func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeginBlock) {
2018-01-26 04:19:33 -08:00
app.msDeliver = app.cms.CacheMultiStore()
app.ctxDeliver = app.NewContext(false, req.Header)
2018-01-24 12:11:14 -08:00
app.valUpdates = nil
if app.beginBlocker != nil {
res = app.beginBlocker(app.ctxDeliver, req)
}
2017-12-21 23:30:44 -08:00
return
}
2018-02-04 12:20:49 -08:00
// Implements ABCI
func (app *BaseApp) CheckTx(txBytes []byte) (res abci.ResponseCheckTx) {
2017-12-01 09:10:17 -08:00
2018-01-26 04:19:33 -08:00
// Decode the Tx.
var result sdk.Result
var tx, err = app.txDecoder(txBytes)
if err != nil {
result = err.Result()
} else {
result = app.runTx(true, txBytes, tx)
}
2018-01-03 17:20:21 -08:00
2017-12-26 17:04:48 -08:00
return abci.ResponseCheckTx{
2018-01-26 06:22:56 -08:00
Code: uint32(result.Code),
Data: result.Data,
Log: result.Log,
2017-12-26 17:04:48 -08:00
GasWanted: result.GasWanted,
Fee: cmn.KI64Pair{
[]byte(result.FeeDenom),
result.FeeAmount,
},
Tags: result.Tags,
}
}
2018-02-04 12:20:49 -08:00
// Implements ABCI
func (app *BaseApp) DeliverTx(txBytes []byte) (res abci.ResponseDeliverTx) {
2017-12-01 09:10:17 -08:00
2018-01-26 04:19:33 -08:00
// Decode the Tx.
var result sdk.Result
var tx, err = app.txDecoder(txBytes)
if err != nil {
result = err.Result()
} else {
result = app.runTx(false, txBytes, tx)
}
2017-12-21 20:19:44 -08:00
// After-handler hooks.
2018-01-26 06:22:56 -08:00
if result.IsOK() {
2017-12-26 17:04:48 -08:00
app.valUpdates = append(app.valUpdates, result.ValidatorUpdates...)
2017-12-21 20:19:44 -08:00
} else {
// Even though the Code is not OK, there will be some side
// effects, like those caused by fee deductions or sequence
// incrementations.
2017-12-01 09:10:17 -08:00
}
2017-12-21 20:19:44 -08:00
// Tell the blockchain engine (i.e. Tendermint).
return abci.ResponseDeliverTx{
2018-01-26 06:22:56 -08:00
Code: uint32(result.Code),
2017-12-26 17:04:48 -08:00
Data: result.Data,
Log: result.Log,
GasWanted: result.GasWanted,
GasUsed: result.GasUsed,
Tags: result.Tags,
2017-12-21 20:19:44 -08:00
}
2017-12-01 09:10:17 -08:00
}
2018-02-17 13:19:34 -08:00
// Mostly for testing
func (app *BaseApp) Check(tx sdk.Tx) (result sdk.Result) {
return app.runTx(true, nil, tx)
}
func (app *BaseApp) Deliver(tx sdk.Tx) (result sdk.Result) {
return app.runTx(false, nil, tx)
}
// txBytes may be nil in some cases, eg. in tests.
// Also, in the future we may support "internal" transactions.
2018-01-26 04:19:33 -08:00
func (app *BaseApp) runTx(isCheckTx bool, txBytes []byte, tx sdk.Tx) (result sdk.Result) {
// Handle any panics.
defer func() {
if r := recover(); r != nil {
2018-01-26 04:19:33 -08:00
log := fmt.Sprintf("Recovered: %v\nstack:\n%v", r, string(debug.Stack()))
result = sdk.ErrInternal(log).Result()
}
}()
2018-01-26 06:22:56 -08:00
// Get the Msg.
var msg = tx.GetMsg()
if msg == nil {
return sdk.ErrInternal("Tx.GetMsg() returned nil").Result()
}
// Validate the Msg.
err := msg.ValidateBasic()
if err != nil {
2018-01-26 04:19:33 -08:00
return err.Result()
}
// Get the context
var ctx sdk.Context
if isCheckTx {
ctx = app.ctxCheck.WithTxBytes(txBytes)
} else {
ctx = app.ctxDeliver.WithTxBytes(txBytes)
}
2018-01-26 04:19:33 -08:00
// TODO: override default ante handler w/ custom ante handler.
// Run the ante handler.
2018-02-14 17:09:00 -08:00
newCtx, result, abort := app.anteHandler(ctx, tx)
if isCheckTx || abort {
return result
}
2018-01-26 05:11:01 -08:00
if !newCtx.IsZero() {
ctx = newCtx
}
// CacheWrap app.msDeliver in case it fails.
msCache := app.msDeliver.CacheMultiStore()
2018-01-26 05:11:01 -08:00
ctx = ctx.WithMultiStore(msCache)
// Match and run route.
2018-01-26 06:22:56 -08:00
msgType := msg.Type()
handler := app.router.Route(msgType)
2018-01-26 06:22:56 -08:00
result = handler(ctx, msg)
2018-01-26 05:11:01 -08:00
// If result was successful, write to app.msDeliver or app.msCheck.
if result.IsOK() {
msCache.Write()
}
return result
}
2018-02-04 12:20:49 -08:00
// Implements ABCI
func (app *BaseApp) EndBlock(req abci.RequestEndBlock) (res abci.ResponseEndBlock) {
if app.endBlocker != nil {
res = app.endBlocker(app.ctxDeliver, req)
} else {
res.ValidatorUpdates = app.valUpdates
}
2017-12-21 20:19:44 -08:00
return
2017-12-01 09:10:17 -08:00
}
2018-02-04 12:20:49 -08:00
// Implements ABCI
func (app *BaseApp) Commit() (res abci.ResponseCommit) {
// Write the Deliver state and commit the MultiStore
2017-12-26 17:04:48 -08:00
app.msDeliver.Write()
2018-01-26 04:19:33 -08:00
commitID := app.cms.Commit()
app.logger.Debug("Commit synced",
"commit", commitID,
)
// Reset the Check state
// NOTE: safe because Tendermint holds a lock on the mempool for Commit.
// Use the header from this latest block.
header := app.ctxDeliver.BlockHeader()
app.msCheck = app.cms.CacheMultiStore()
app.ctxCheck = app.NewContext(true, header)
2017-12-26 17:04:48 -08:00
return abci.ResponseCommit{
Data: commitID.Hash,
}
2017-12-01 09:10:17 -08:00
}