cosmos-sdk/app/base.go

278 lines
6.8 KiB
Go
Raw Normal View History

package app
import (
2017-12-01 09:10:17 -08:00
"bytes"
"fmt"
"os"
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
abci "github.com/tendermint/abci/types"
2017-12-01 09:10:17 -08:00
cmn "github.com/tendermint/tmlibs/common"
"github.com/tendermint/tmlibs/log"
sdk "github.com/cosmos/cosmos-sdk"
)
2017-12-01 09:10:17 -08:00
const mainKeyHeader = "header"
// BaseApp - The ABCI application
type BaseApp struct {
2017-12-01 09:10:17 -08:00
logger log.Logger
// App name from abci.Info
name string
// DeliverTx (main) state
store MultiStore
2017-12-01 09:10:17 -08:00
// CheckTx state
storeCheck CacheMultiStore
2017-12-01 09:10:17 -08:00
// Current block header
header *abci.Header
2017-12-01 09:10:17 -08:00
// Handler for CheckTx and DeliverTx.
handler sdk.Handler
// Cached validator changes from DeliverTx
valSetDiff []abci.Validator
}
var _ abci.Application = &BaseApp{}
2017-12-01 09:10:17 -08:00
// CONTRACT: There exists a "main" KVStore.
func NewBaseApp(name string, store CommitMultiStore) (*BaseApp, error) {
2017-12-01 09:10:17 -08:00
if store.GetKVStore("main") == nil {
2017-12-01 09:10:17 -08:00
return nil, errors.New("BaseApp expects MultiStore with 'main' KVStore")
}
logger := makeDefaultLogger()
lastCommitID := store.LastCommitID()
curVersion := store.CurrentVersion()
main := store.GetKVStore("main")
2017-12-01 09:10:17 -08:00
header := (*abci.Header)(nil)
storeCheck := store.CacheMultiStore()
2017-12-01 09:10:17 -08:00
// SANITY
if curVersion != lastCommitID.Version+1 {
panic("CurrentVersion != LastCommitID.Version+1")
}
// If we've committed before, we expect store.GetKVStore("main").Get("header")
2017-12-01 09:10:17 -08:00
if !lastCommitID.IsZero() {
headerBytes, ok := main.Get(mainKeyHeader)
if !ok {
return nil, errors.New(fmt.Sprintf("Version > 0 but missing key %s", mainKeyHeader))
}
err = proto.Unmarshal(headerBytes, header)
if err != nil {
return nil, errors.Wrap(err, "Failed to parse Header")
}
// SANITY: Validate Header
if header.Height != curVersion-1 {
errStr := fmt.Sprintf("Expected header.Height %v but got %v", version, headerHeight)
panic(errStr)
}
}
return &BaseApp{
logger: logger,
name: name,
store: store,
storeCheck: storeCheck,
header: header,
hander: nil, // set w/ .WithHandler()
valSetDiff: nil,
}
}
func (app *BaseApp) WithHandler(handler sdk.Handler) *BaseApp {
2017-12-01 09:10:17 -08:00
app.handler = handler
}
//----------------------------------------
// DeliverTx - ABCI - dispatches to the handler
2017-12-01 09:10:17 -08:00
func (app *BaseApp) DeliverTx(txBytes []byte) abci.ResponseDeliverTx {
// Initialize arguments to Handler.
var isCheckTx = false
var ctx = sdk.NewContext(app.header, isCheckTx, txBytes)
var store = app.store
var tx Tx = nil // nil until a decorator parses one.
// Run the handler.
var result = app.handler(ctx, app.store, tx)
// After-handler hooks.
// TODO move to app.afterHandler(...).
if result.Code == abci.CodeType_OK {
// XXX No longer "diff", we need to replace old entries.
app.ValSetDiff = append(app.ValSetDiff, result.ValSetDiff)
} else {
// Even though the Code is not OK, there will be some side effects,
// like those caused by fee deductions or sequence incrementations.
}
// Tell the blockchain engine (i.e. Tendermint).
2017-12-01 09:10:17 -08:00
return abci.ResponseDeliverTx{
Code: result.Code,
Data: result.Data,
Log: result.Log,
Tags: result.Tags,
2017-12-01 09:10:17 -08:00
}
}
// CheckTx - ABCI - dispatches to the handler
2017-12-01 09:10:17 -08:00
func (app *BaseApp) CheckTx(txBytes []byte) abci.ResponseCheckTx {
// Initialize arguments to Handler.
var isCheckTx = true
var ctx = sdk.NewContext(app.header, isCheckTx, txBytes)
var store = app.store
var tx Tx = nil // nil until a decorator parses one.
// Run the handler.
var result = app.handler(ctx, app.store, tx)
// Tell the blockchain engine (i.e. Tendermint).
return abci.ResponseDeliverTx{
Code: result.Code,
Data: result.Data,
Log: result.Log,
Gas: result.Gas,
FeeDenom: result.FeeDenom,
FeeAmount: result.FeeAmount,
}
}
2017-12-01 09:10:17 -08:00
// Info - ABCI
func (app *BaseApp) Info(req abci.RequestInfo) abci.ResponseInfo {
lastCommitID := app.store.LastCommitID()
2017-12-01 09:10:17 -08:00
return abci.ResponseInfo{
Data: app.Name,
LastBlockHeight: lastCommitID.Version,
LastBlockAppHash: lastCommitID.Hash,
}
}
// SetOption - ABCI
func (app *BaseApp) SetOption(key string, value string) string {
2017-12-01 09:10:17 -08:00
return "Not Implemented"
}
// Query - ABCI
func (app *BaseApp) Query(reqQuery abci.RequestQuery) (resQuery abci.ResponseQuery) {
/*
XXX Make this work with MultiStore.
XXX It will require some interfaces updates in store/types.go.
if len(reqQuery.Data) == 0 {
resQuery.Log = "Query cannot be zero length"
resQuery.Code = abci.CodeType_EncodingError
return
2017-12-01 09:10:17 -08:00
}
// set the query response height to current
tree := app.state.Committed()
height := reqQuery.Height
if height == 0 {
// TODO: once the rpc actually passes in non-zero
// heights we can use to query right after a tx
// we must retrun most recent, even if apphash
// is not yet in the blockchain
withProof := app.CommittedHeight() - 1
if tree.Tree.VersionExists(withProof) {
height = withProof
} else {
height = app.CommittedHeight()
2017-12-01 09:10:17 -08:00
}
}
resQuery.Height = height
switch reqQuery.Path {
case "/store", "/key": // Get by key
key := reqQuery.Data // Data holds the key bytes
resQuery.Key = key
if reqQuery.Prove {
value, proof, err := tree.GetVersionedWithProof(key, height)
if err != nil {
resQuery.Log = err.Error()
break
}
resQuery.Value = value
resQuery.Proof = proof.Bytes()
} else {
value := tree.Get(key)
resQuery.Value = value
}
2017-12-01 09:10:17 -08:00
default:
resQuery.Code = abci.CodeType_UnknownRequest
resQuery.Log = cmn.Fmt("Unexpected Query path: %v", reqQuery.Path)
}
return
2017-12-01 09:10:17 -08:00
*/
}
// Commit implements abci.Application
func (app *BaseApp) Commit() (res abci.Result) {
2017-12-01 09:10:17 -08:00
/*
hash, err := app.state.Commit(app.height)
if err != nil {
2017-12-01 09:10:17 -08:00
// die if we can't commit, not to recover
panic(err)
}
2017-12-01 09:10:17 -08:00
app.logger.Debug("Commit synced",
"height", app.height,
"hash", fmt.Sprintf("%X", hash),
)
if app.state.Size() == 0 {
return abci.NewResultOK(nil, "Empty hash for empty tree")
}
return abci.NewResultOK(hash, "")
*/
}
// InitChain - ABCI
func (app *BaseApp) InitChain(req abci.RequestInitChain) {}
2017-12-01 09:10:17 -08:00
// BeginBlock - ABCI
func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) {
app.header = req.Header
2017-12-01 09:10:17 -08:00
}
// EndBlock - ABCI
// Returns a list of all validator changes made in this block
func (app *BaseApp) EndBlock(height uint64) (res abci.ResponseEndBlock) {
// TODO: Compress duplicates
res.Diffs = app.valSetDiff
app.valSetDiff = nil
2017-12-01 09:10:17 -08:00
return
}
// 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")
}