cosmos-sdk/baseapp/baseapp.go

385 lines
8.8 KiB
Go
Raw Normal View History

package baseapp
import (
2017-12-01 09:10:17 -08:00
"bytes"
"fmt"
"os"
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"
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
// BaseApp - The ABCI application
type BaseApp struct {
2017-12-01 09:10:17 -08:00
logger log.Logger
// Application name from abci.Info
2017-12-01 09:10:17 -08:00
name string
// Common DB backend
db dbm.DB
2017-12-21 23:30:44 -08:00
// Main (uncached) state
2018-01-26 04:19:33 -08:00
cms sdk.CommitMultiStore
2017-12-01 09:10:17 -08:00
2018-01-12 13:59:19 -08:00
// Unmarshal []byte into sdk.Tx
txDecoder sdk.TxDecoder
// Ante handler for fee and auth.
2018-01-12 13:59:19 -08:00
defaultAnteHandler sdk.AnteHandler
// Handle any kind of message.
router Router
//--------------------
// Volatile
2018-01-26 04:19:33 -08:00
// CheckTx state, a cache-wrap of `.cms`.
2018-01-12 13:59:19 -08:00
msCheck sdk.CacheMultiStore
2017-12-01 09:10:17 -08:00
2018-01-26 04:19:33 -08:00
// DeliverTx state, a cache-wrap of `.cms`.
2018-01-12 13:59:19 -08:00
msDeliver sdk.CacheMultiStore
2017-12-21 23:30:44 -08:00
// Current block header
2018-01-24 12:11:14 -08:00
header *abci.Header
2017-12-01 09:10:17 -08:00
// Cached validator changes from DeliverTx.
2017-12-20 17:34:51 -08:00
valUpdates []abci.Validator
}
var _ abci.Application = &BaseApp{}
func NewBaseApp(name string) *BaseApp {
var baseapp = &BaseApp{
2017-12-19 21:04:40 -08:00
logger: makeDefaultLogger(),
name: name,
db: nil,
2018-01-26 04:19:33 -08:00
cms: nil,
router: NewRouter(),
2017-12-01 09:10:17 -08:00
}
baseapp.initDB()
baseapp.initMultiStore()
return baseapp
}
// Create the underlying leveldb datastore which will
// persist the Merkle tree inner & leaf nodes.
func (app *BaseApp) initDB() {
db, err := dbm.NewGoLevelDB(app.name, "data")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
app.db = db
}
func (app *BaseApp) initMultiStore() {
2018-01-26 04:19:33 -08:00
cms := store.NewCommitMultiStore(app.db)
app.cms = cms
2017-12-19 21:04:40 -08:00
}
func (app *BaseApp) Name() string {
2017-12-21 23:30:44 -08:00
return app.name
}
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
}
func (app *BaseApp) SetTxDecoder(txDecoder sdk.TxDecoder) {
app.txDecoder = txDecoder
2017-12-19 21:04:40 -08:00
}
func (app *BaseApp) SetDefaultAnteHandler(ah sdk.AnteHandler) {
app.defaultAnteHandler = ah
2018-01-03 17:20:21 -08:00
}
func (app *BaseApp) Router() Router {
return app.router
2017-12-19 21:04:40 -08:00
}
2017-12-01 09:10:17 -08:00
/* TODO consider:
func (app *BaseApp) SetBeginBlocker(...) {}
func (app *BaseApp) SetEndBlocker(...) {}
func (app *BaseApp) SetInitStater(...) {}
*/
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
}
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
}
2017-12-26 17:04:48 -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
}
// 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-01-26 04:19:33 -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-01-24 12:11:14 -08:00
var header *abci.Header
2017-12-01 09:10:17 -08:00
2017-12-19 21:04:40 -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
}
2017-12-21 23:30:44 -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-01-24 12:11:14 -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
// Set BaseApp state.
2017-12-20 17:34:51 -08:00
app.header = header
2017-12-26 17:04:48 -08:00
app.msCheck = nil
app.msDeliver = nil
2017-12-20 17:34:51 -08:00
app.valUpdates = nil
return nil
2017-12-01 09:10:17 -08:00
}
//----------------------------------------
2018-01-24 11:47:51 -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-01-24 11:47:51 -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-01-24 11:47:51 -08:00
// Implements ABCI.
func (app *BaseApp) InitChain(req abci.RequestInitChain) (res abci.ResponseInitChain) {
2017-12-21 20:19:44 -08:00
// TODO: Use req.Validators
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-01-24 11:47:51 -08:00
// Implements ABCI.
func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeginBlock) {
2018-01-24 12:11:14 -08:00
// NOTE: For consistency we should unset these upon EndBlock.
app.header = &req.Header
2018-01-26 04:19:33 -08:00
app.msDeliver = app.cms.CacheMultiStore()
app.msCheck = app.cms.CacheMultiStore()
2018-01-24 12:11:14 -08:00
app.valUpdates = nil
2017-12-21 23:30:44 -08:00
return
}
2018-01-24 11:47:51 -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-01-24 11:47:51 -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-01-26 04:19:33 -08:00
// txBytes may be nil in some cases, for example, when tx is
// coming from TestApp. Also, in the future we may support
// "internal" transactions.
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()
}
2018-01-26 04:19:33 -08:00
// Construct a Context.
var ctx = app.NewContext(isCheckTx, txBytes)
2018-01-26 04:19:33 -08:00
// TODO: override default ante handler w/ custom ante handler.
// Run the ante handler.
2018-01-26 05:11:01 -08:00
newCtx, result, abort := app.defaultAnteHandler(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.getMultiStore(isCheckTx).CacheMultiStore()
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-01-24 11:47:51 -08:00
// Implements ABCI.
func (app *BaseApp) EndBlock(req abci.RequestEndBlock) (res abci.ResponseEndBlock) {
2017-12-21 20:19:44 -08:00
res.ValidatorUpdates = app.valUpdates
app.valUpdates = nil
2018-01-24 12:11:14 -08:00
app.header = nil
app.msDeliver = nil
app.msCheck = nil
2017-12-21 20:19:44 -08:00
return
2017-12-01 09:10:17 -08:00
}
2018-01-24 11:47:51 -08:00
// Implements ABCI.
func (app *BaseApp) Commit() (res abci.ResponseCommit) {
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,
)
2017-12-26 17:04:48 -08:00
return abci.ResponseCommit{
Data: commitID.Hash,
}
2017-12-01 09:10:17 -08:00
}
2017-12-21 20:19:44 -08:00
//----------------------------------------
// Misc.
2017-12-01 09:10:17 -08:00
2018-01-26 05:11:01 -08:00
func (app *BaseApp) getMultiStore(isCheckTx bool) sdk.MultiStore {
if isCheckTx {
return app.msCheck
} else {
return app.msDeliver
}
}
// Return index of list with validator of same PubKey, or -1 if no match
2017-12-01 09:10:17 -08:00
func pubKeyIndex(val *abci.Validator, list []*abci.Validator) int {
for i, v := range list {
if bytes.Equal(val.PubKey, v.PubKey) {
return i
}
}
return -1
}
// Make a simple default logger
// TODO: Make log capturable for each transaction, and return it in
// ResponseDeliverTx.Log and ResponseCheckTx.Log.
func makeDefaultLogger() log.Logger {
return log.NewTMLogger(log.NewSyncWriter(os.Stdout)).With("module", "sdk/app")
}