cosmos-sdk/baseapp/baseapp.go

732 lines
22 KiB
Go
Raw Normal View History

package baseapp
import (
2017-12-01 09:10:17 -08:00
"fmt"
"io"
2018-01-26 04:19:33 -08:00
"runtime/debug"
2018-05-09 13:25:13 -07:00
"strings"
2017-12-01 09:10:17 -08:00
"github.com/pkg/errors"
2018-02-14 08:16:06 -08:00
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/tmhash"
dbm "github.com/tendermint/tendermint/libs/db"
"github.com/tendermint/tendermint/libs/log"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store"
2018-01-12 13:59:19 -08:00
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/version"
)
// Key to store the header in the DB itself.
// Use the db directly instead of a store to avoid
// conflicts with handlers writing to the store
// and to avoid affecting the Merkle root.
var dbHeaderKey = []byte("header")
2017-12-01 09:10:17 -08:00
2018-05-15 17:18:25 -07:00
// Enum mode for app.runTx
type runTxMode uint8
2018-05-15 17:06:17 -07:00
const (
// Check a transaction
2018-05-15 17:18:25 -07:00
runTxModeCheck runTxMode = iota
2018-05-15 17:06:17 -07:00
// Simulate a transaction
2018-05-15 17:18:25 -07:00
runTxModeSimulate runTxMode = iota
2018-05-15 17:06:17 -07:00
// Deliver a transaction
2018-05-15 17:18:25 -07:00
runTxModeDeliver runTxMode = iota
2018-05-15 17:06:17 -07:00
)
// BaseApp reflects the ABCI application implementation.
type BaseApp struct {
// initialized on creation
2018-07-31 18:48:32 -07:00
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-08-15 17:59:15 -07:00
queryRouter QueryRouter // router for redirecting query calls
2018-07-31 18:48:32 -07:00
txDecoder sdk.TxDecoder // unmarshal []byte into sdk.Tx
2018-07-18 16:24:16 -07:00
2018-02-17 16:24:40 -08:00
anteHandler sdk.AnteHandler // ante handler for fee and auth
// may be nil
2018-05-15 07:00:17 -07:00
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
addrPeerFilter sdk.PeerFilter // filter peers by address and port
pubkeyPeerFilter sdk.PeerFilter // filter peers by public key
//--------------------
// Volatile
// checkState is set on initialization and reset on Commit.
// deliverState is set in InitChain and BeginBlock and cleared on Commit.
// See methods setCheckState and setDeliverState.
checkState *state // for CheckTx
deliverState *state // for DeliverTx
voteInfos []abci.VoteInfo // absent validators from begin block
// minimum fees for spam prevention
minimumFees sdk.Coins
// flag for sealing
sealed bool
}
var _ abci.Application = (*BaseApp)(nil)
// NewBaseApp returns a reference to an initialized BaseApp.
//
// TODO: Determine how to use a flexible and robust configuration paradigm that
// allows for sensible defaults while being highly configurable
// (e.g. functional options).
//
// NOTE: The db is used to store the version number for now.
2018-07-18 16:24:16 -07:00
// Accepts a user-defined txDecoder
// Accepts variable number of option functions, which act on the BaseApp to set configuration choices
2018-07-18 16:24:16 -07:00
func NewBaseApp(name string, logger log.Logger, db dbm.DB, txDecoder sdk.TxDecoder, options ...func(*BaseApp)) *BaseApp {
app := &BaseApp{
2018-07-31 18:48:32 -07:00
Logger: logger,
name: name,
db: db,
cms: store.NewCommitMultiStore(db),
router: NewRouter(),
2018-08-15 17:59:15 -07:00
queryRouter: NewQueryRouter(),
2018-07-31 18:48:32 -07:00
txDecoder: txDecoder,
2017-12-01 09:10:17 -08:00
}
for _, option := range options {
option(app)
}
return app
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
}
// SetCommitMultiStoreTracer sets the store tracer on the BaseApp's underlying
// CommitMultiStore.
func (app *BaseApp) SetCommitMultiStoreTracer(w io.Writer) {
app.cms.WithTracer(w)
}
// Mount IAVL stores to the provided keys in the BaseApp multistore
2018-02-14 17:09:00 -08:00
func (app *BaseApp) MountStoresIAVL(keys ...*sdk.KVStoreKey) {
for _, key := range keys {
app.MountStore(key, sdk.StoreTypeIAVL)
}
}
// Mount stores to the provided keys in the BaseApp multistore
func (app *BaseApp) MountStoresTransient(keys ...*sdk.TransientStoreKey) {
for _, key := range keys {
app.MountStore(key, sdk.StoreTypeTransient)
}
}
// Mount a store to the provided key in the BaseApp multistore, using a specified DB
func (app *BaseApp) MountStoreWithDB(key sdk.StoreKey, typ sdk.StoreType, db dbm.DB) {
app.cms.MountStoreWithDB(key, typ, db)
2018-01-24 11:47:51 -08:00
}
// Mount a store to the provided key in the BaseApp multistore, using the default DB
func (app *BaseApp) MountStore(key sdk.StoreKey, typ sdk.StoreType) {
app.cms.MountStoreWithDB(key, typ, nil)
2018-01-24 11:47:51 -08:00
}
2018-02-14 08:16:06 -08:00
// load latest application version
func (app *BaseApp) LoadLatestVersion(mainKey sdk.StoreKey) error {
err := app.cms.LoadLatestVersion()
if err != nil {
return err
}
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 {
err := app.cms.LoadVersion(version)
if err != nil {
return err
}
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
}
// the last committed 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-02-14 08:16:06 -08:00
// main store should exist.
// TODO: we don't actually need the main store here
main := app.cms.GetKVStore(mainKey)
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
}
// Needed for `gaiad export`, which inits from store but never calls initchain
2018-07-23 16:55:09 -07:00
app.setCheckState(abci.Header{})
app.Seal()
2017-12-20 17:34:51 -08:00
return nil
2017-12-01 09:10:17 -08:00
}
// SetMinimumFees sets the minimum fees.
func (app *BaseApp) SetMinimumFees(fees sdk.Coins) { app.minimumFees = fees }
// 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.checkState.ms, header, true, app.Logger).WithMinimumFees(app.minimumFees)
}
return sdk.NewContext(app.deliverState.ms, header, false, app.Logger)
}
type state struct {
ms sdk.CacheMultiStore
ctx sdk.Context
}
func (st *state) CacheMultiStore() sdk.CacheMultiStore {
return st.ms.CacheMultiStore()
}
func (app *BaseApp) setCheckState(header abci.Header) {
ms := app.cms.CacheMultiStore()
app.checkState = &state{
ms: ms,
ctx: sdk.NewContext(ms, header, true, app.Logger).WithMinimumFees(app.minimumFees),
}
}
func (app *BaseApp) setDeliverState(header abci.Header) {
ms := app.cms.CacheMultiStore()
app.deliverState = &state{
ms: ms,
ctx: sdk.NewContext(ms, header, false, app.Logger),
}
}
//______________________________________________________________________________
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) {
// Initialize the deliver state and check state with ChainID and run initChain
app.setDeliverState(abci.Header{ChainID: req.ChainId})
app.setCheckState(abci.Header{ChainID: req.ChainId})
if app.initChainer == nil {
2018-02-15 06:35:46 -08:00
return
}
res = app.initChainer(app.deliverState.ctx, req)
2018-02-16 17:58:51 -08:00
// NOTE: we don't commit, but BeginBlock for block 1
// starts from this deliverState
2017-12-21 23:30:44 -08:00
return
2017-12-21 20:19:44 -08:00
}
2018-05-15 07:00:17 -07:00
// Filter peers by address / port
func (app *BaseApp) FilterPeerByAddrPort(info string) abci.ResponseQuery {
if app.addrPeerFilter != nil {
return app.addrPeerFilter(info)
}
return abci.ResponseQuery{}
}
// Filter peers by public key
func (app *BaseApp) FilterPeerByPubKey(info string) abci.ResponseQuery {
if app.pubkeyPeerFilter != nil {
return app.pubkeyPeerFilter(info)
}
return abci.ResponseQuery{}
}
2018-08-15 17:59:15 -07:00
// Splits a string path using the delimter '/'. i.e. "this/is/funny" becomes []string{"this", "is", "funny"}
func splitPath(requestPath string) (path []string) {
path = strings.Split(requestPath, "/")
2018-05-15 17:06:17 -07:00
// first element is empty string
if len(path) > 0 && path[0] == "" {
path = path[1:]
}
return path
}
// Implements ABCI.
// Delegates to CommitMultiStore if it implements Queryable
func (app *BaseApp) Query(req abci.RequestQuery) (res abci.ResponseQuery) {
path := splitPath(req.Path)
2018-07-09 14:44:01 -07:00
if len(path) == 0 {
msg := "no query path provided"
return sdk.ErrUnknownRequest(msg).QueryResult()
}
switch path[0] {
2018-05-10 11:20:34 -07:00
// "/app" prefix for special application queries
2018-07-09 14:44:01 -07:00
case "app":
return handleQueryApp(app, path, req)
case "store":
return handleQueryStore(app, path, req)
case "p2p":
return handleQueryP2P(app, path, req)
2018-07-31 18:48:32 -07:00
case "custom":
return handleQueryCustom(app, path, req)
2018-07-09 14:44:01 -07:00
}
msg := "unknown query path"
return sdk.ErrUnknownRequest(msg).QueryResult()
}
func handleQueryApp(app *BaseApp, path []string, req abci.RequestQuery) (res abci.ResponseQuery) {
if len(path) >= 2 {
2018-05-09 13:25:13 -07:00
var result sdk.Result
2018-05-15 17:06:17 -07:00
switch path[1] {
case "simulate":
2018-05-09 13:25:13 -07:00
txBytes := req.Data
tx, err := app.txDecoder(txBytes)
if err != nil {
result = err.Result()
2018-05-11 11:02:05 -07:00
} else {
result = app.Simulate(tx)
2018-05-09 13:25:13 -07:00
}
case "version":
return abci.ResponseQuery{
2018-11-16 09:12:24 -08:00
Code: uint32(sdk.CodeOK),
Codespace: string(sdk.CodespaceRoot),
Value: []byte(version.GetVersion()),
}
2018-05-09 13:25:13 -07:00
default:
result = sdk.ErrUnknownRequest(fmt.Sprintf("Unknown query: %s", path)).Result()
}
2018-07-12 19:06:54 -07:00
2018-07-18 16:24:16 -07:00
// Encode with json
value := codec.Cdc.MustMarshalBinaryLengthPrefixed(result)
2018-05-09 13:25:13 -07:00
return abci.ResponseQuery{
2018-11-16 09:12:24 -08:00
Code: uint32(sdk.CodeOK),
Codespace: string(sdk.CodespaceRoot),
Value: value,
2018-05-09 13:25:13 -07:00
}
}
2018-07-09 14:44:01 -07:00
msg := "Expected second parameter to be either simulate or version, neither was present"
return sdk.ErrUnknownRequest(msg).QueryResult()
}
func handleQueryStore(app *BaseApp, path []string, req abci.RequestQuery) (res abci.ResponseQuery) {
2018-05-10 11:20:34 -07:00
// "/store" prefix for store queries
2018-07-09 14:44:01 -07:00
queryable, ok := app.cms.(sdk.Queryable)
if !ok {
msg := "multistore doesn't support queries"
return sdk.ErrUnknownRequest(msg).QueryResult()
2018-05-10 11:20:34 -07:00
}
2018-07-09 14:44:01 -07:00
req.Path = "/" + strings.Join(path[1:], "/")
return queryable.Query(req)
}
2018-08-31 15:22:37 -07:00
// nolint: unparam
2018-07-09 14:44:01 -07:00
func handleQueryP2P(app *BaseApp, path []string, req abci.RequestQuery) (res abci.ResponseQuery) {
2018-05-15 07:00:17 -07:00
// "/p2p" prefix for p2p queries
2018-07-09 14:44:01 -07:00
if len(path) >= 4 {
2018-05-15 17:06:17 -07:00
if path[1] == "filter" {
if path[2] == "addr" {
return app.FilterPeerByAddrPort(path[3])
2018-05-15 07:00:17 -07:00
}
2018-05-15 17:06:17 -07:00
if path[2] == "pubkey" {
// TODO: this should be changed to `id`
// NOTE: this changed in tendermint and we didn't notice...
2018-05-15 17:06:17 -07:00
return app.FilterPeerByPubKey(path[3])
2018-05-15 07:00:17 -07:00
}
2018-07-09 14:44:01 -07:00
} else {
msg := "Expected second parameter to be filter"
return sdk.ErrUnknownRequest(msg).QueryResult()
2018-05-15 07:00:17 -07:00
}
}
2018-07-09 14:44:01 -07:00
msg := "Expected path is p2p filter <addr|pubkey> <parameter>"
2018-05-10 11:20:34 -07:00
return sdk.ErrUnknownRequest(msg).QueryResult()
2017-12-21 20:19:44 -08:00
}
2018-07-31 18:48:32 -07:00
func handleQueryCustom(app *BaseApp, path []string, req abci.RequestQuery) (res abci.ResponseQuery) {
2018-08-15 17:59:15 -07:00
// path[0] should be "custom" because "/custom" prefix is required for keeper queries.
// the queryRouter routes using path[1]. For example, in the path "custom/gov/proposal", queryRouter routes using "gov"
if len(path) < 2 || path[1] == "" {
return sdk.ErrUnknownRequest("No route for custom query specified").QueryResult()
2018-08-16 18:35:17 -07:00
}
2018-08-15 17:59:15 -07:00
querier := app.queryRouter.Route(path[1])
if querier == nil {
return sdk.ErrUnknownRequest(fmt.Sprintf("no custom querier found for route %s", path[1])).QueryResult()
}
ctx := sdk.NewContext(app.cms.CacheMultiStore(), app.checkState.ctx.BlockHeader(), true, app.Logger).
WithMinimumFees(app.minimumFees)
2018-08-15 17:59:15 -07:00
// Passes the rest of the path as an argument to the querier.
// For example, in the path "custom/gov/proposal/test", the gov querier gets []string{"proposal", "test"} as the path
2018-08-03 12:55:00 -07:00
resBytes, err := querier(ctx, path[2:], req)
if err != nil {
return abci.ResponseQuery{
2018-11-16 09:12:24 -08:00
Code: uint32(err.Code()),
Codespace: string(err.Codespace()),
Log: err.ABCILog(),
2018-08-03 12:55:00 -07:00
}
}
return abci.ResponseQuery{
2018-11-16 09:12:24 -08:00
Code: uint32(sdk.CodeOK),
2018-08-03 12:55:00 -07:00
Value: resBytes,
}
2018-07-31 18:48:32 -07:00
}
// BeginBlock implements the ABCI application interface.
func (app *BaseApp) BeginBlock(req abci.RequestBeginBlock) (res abci.ResponseBeginBlock) {
if app.cms.TracingEnabled() {
app.cms.ResetTraceContext()
app.cms.WithTracingContext(sdk.TraceContext(
map[string]interface{}{"blockHeight": req.Header.Height},
))
}
// Initialize the DeliverTx state. If this is the first block, it should
// already be initialized in InitChain. Otherwise app.deliverState will be
// nil, since it is reset on Commit.
if app.deliverState == nil {
app.setDeliverState(req.Header)
} else {
// In the first block, app.deliverState.ctx will already be initialized
// by InitChain. Context is now updated with Header information.
app.deliverState.ctx = app.deliverState.ctx.WithBlockHeader(req.Header).WithBlockHeight(req.Header.Height)
}
if app.beginBlocker != nil {
res = app.beginBlocker(app.deliverState.ctx, req)
}
2018-06-04 16:42:01 -07:00
// set the signed validators for addition to context in deliverTx
// TODO: communicate this result to the address to pubkey map in slashing
app.voteInfos = req.LastCommitInfo.GetVotes()
2017-12-21 23:30:44 -08:00
return
}
// CheckTx implements ABCI
// CheckTx runs the "basic checks" to see whether or not a transaction can possibly be executed,
// first decoding, then the ante handler (which checks signatures/fees/ValidateBasic),
// then finally the route match to see whether a handler exists. CheckTx does not run the actual
// Msg handler function(s).
func (app *BaseApp) CheckTx(txBytes []byte) (res abci.ResponseCheckTx) {
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 {
2018-05-15 17:18:25 -07:00
result = app.runTx(runTxModeCheck, txBytes, tx)
2018-01-26 04:19:33 -08:00
}
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,
GasUsed: result.GasUsed,
Tags: result.Tags,
}
}
2018-02-04 12:20:49 -08:00
// Implements ABCI
func (app *BaseApp) DeliverTx(txBytes []byte) (res abci.ResponseDeliverTx) {
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 {
2018-05-15 17:18:25 -07:00
result = app.runTx(runTxModeDeliver, txBytes, tx)
2018-01-26 04:19:33 -08:00
}
2017-12-21 20:19:44 -08:00
// Even though the Result.Code is not OK, there are still effects,
// namely fee deductions and sequence incrementing.
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),
2018-11-16 09:12:24 -08:00
Codespace: string(result.Codespace),
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
}
// Basic validator for msgs
2018-07-09 16:16:43 -07:00
func validateBasicTxMsgs(msgs []sdk.Msg) sdk.Error {
if msgs == nil || len(msgs) == 0 {
// TODO: probably shouldn't be ErrInternal. Maybe new ErrInvalidMessage, or ?
return sdk.ErrInternal("Tx.GetMsgs() must return at least one message in list")
}
for _, msg := range msgs {
// Validate the Msg.
err := msg.ValidateBasic()
if err != nil {
return err
}
}
2018-07-09 16:16:43 -07:00
return nil
}
// retrieve the context for the ante handler and store the tx bytes; store
// the vote infos if the tx runs within the deliverTx() state.
func (app *BaseApp) getContextForAnte(mode runTxMode, txBytes []byte) (ctx sdk.Context) {
ctx = app.getState(mode).ctx.WithTxBytes(txBytes)
2018-08-24 06:57:45 -07:00
if mode == runTxModeDeliver {
ctx = ctx.WithVoteInfos(app.voteInfos)
}
return
}
// Iterates through msgs and executes them
func (app *BaseApp) runMsgs(ctx sdk.Context, msgs []sdk.Msg, mode runTxMode) (result sdk.Result) {
// accumulate results
logs := make([]string, 0, len(msgs))
var data []byte // NOTE: we just append them all (?!)
var tags sdk.Tags // also just append them all
2018-11-16 09:12:24 -08:00
var code sdk.CodeType
var codespace sdk.CodespaceType
for msgIdx, msg := range msgs {
// Match route.
msgRoute := msg.Route()
handler := app.router.Route(msgRoute)
if handler == nil {
return sdk.ErrUnknownRequest("Unrecognized Msg type: " + msgRoute).Result()
}
var msgResult sdk.Result
// Skip actual execution for CheckTx
if mode != runTxModeCheck {
msgResult = handler(ctx, msg)
}
msgResult.Tags = append(msgResult.Tags, sdk.MakeTag("action", []byte(msg.Type())))
// NOTE: GasWanted is determined by ante handler and
// GasUsed by the GasMeter
// Append Data and Tags
data = append(data, msgResult.Data...)
tags = append(tags, msgResult.Tags...)
// Stop execution and return on first failed message.
if !msgResult.IsOK() {
logs = append(logs, fmt.Sprintf("Msg %d failed: %s", msgIdx, msgResult.Log))
code = msgResult.Code
2018-11-16 09:12:24 -08:00
codespace = msgResult.Codespace
break
}
// Construct usable logs in multi-message transactions.
logs = append(logs, fmt.Sprintf("Msg %d: %s", msgIdx, msgResult.Log))
}
// Set the final gas values.
result = sdk.Result{
2018-11-16 09:12:24 -08:00
Code: code,
Codespace: codespace,
Data: data,
Log: strings.Join(logs, "\n"),
GasUsed: ctx.GasMeter().GasConsumed(),
// TODO: FeeAmount/FeeDenom
Tags: tags,
}
return result
}
// Returns the applicantion's deliverState if app is in runTxModeDeliver,
// otherwise it returns the application's checkstate.
func (app *BaseApp) getState(mode runTxMode) *state {
if mode == runTxModeCheck || mode == runTxModeSimulate {
return app.checkState
}
2018-07-09 16:27:51 -07:00
return app.deliverState
}
func (app *BaseApp) initializeContext(ctx sdk.Context, mode runTxMode) sdk.Context {
2018-08-24 06:57:45 -07:00
if mode == runTxModeSimulate {
ctx = ctx.WithMultiStore(app.getState(runTxModeSimulate).CacheMultiStore())
}
2018-08-24 06:57:45 -07:00
return ctx
}
// cacheTxContext returns a new context based off of the provided context with a
// cache wrapped multi-store and the store itself to allow the caller to write
// changes from the cached multi-store.
func (app *BaseApp) cacheTxContext(
ctx sdk.Context, txBytes []byte, mode runTxMode,
) (sdk.Context, sdk.CacheMultiStore) {
msCache := app.getState(mode).CacheMultiStore()
if msCache.TracingEnabled() {
msCache = msCache.WithTracingContext(
sdk.TraceContext(
map[string]interface{}{
"txHash": fmt.Sprintf("%X", tmhash.Sum(txBytes)),
},
),
).(sdk.CacheMultiStore)
}
return ctx.WithMultiStore(msCache), msCache
}
// runTx processes a transaction. The transactions is proccessed via an
// anteHandler. The provided txBytes may be nil in some cases, eg. in tests. For
// further details on transaction execution, reference the BaseApp SDK
// documentation.
2018-05-15 17:18:25 -07:00
func (app *BaseApp) runTx(mode runTxMode, txBytes []byte, tx sdk.Tx) (result sdk.Result) {
// NOTE: GasWanted should be returned by the AnteHandler. GasUsed is
// determined by the GasMeter. We need access to the context to get the gas
// meter so we initialize upfront.
var gasWanted int64
ctx := app.getContextForAnte(mode, txBytes)
ctx = app.initializeContext(ctx, mode)
defer func() {
if r := recover(); r != nil {
switch rType := r.(type) {
2018-05-08 08:46:02 -07:00
case sdk.ErrorOutOfGas:
log := fmt.Sprintf("out of gas in location: %v", rType.Descriptor)
2018-05-08 08:46:02 -07:00
result = sdk.ErrOutOfGas(log).Result()
default:
log := fmt.Sprintf("recovered: %v\nstack:\n%v", r, string(debug.Stack()))
2018-05-08 08:46:02 -07:00
result = sdk.ErrInternal(log).Result()
}
}
result.GasWanted = gasWanted
result.GasUsed = ctx.GasMeter().GasConsumed()
}()
var msgs = tx.GetMsgs()
if err := validateBasicTxMsgs(msgs); err != nil {
2018-07-09 16:16:43 -07:00
return err.Result()
}
// Execute the ante handler if one is defined.
2018-02-28 19:17:48 -08:00
if app.anteHandler != nil {
var anteCtx sdk.Context
var msCache sdk.CacheMultiStore
// Cache wrap context before anteHandler call in case it aborts.
// This is required for both CheckTx and DeliverTx.
// https://github.com/cosmos/cosmos-sdk/issues/2772
// NOTE: Alternatively, we could require that anteHandler ensures that
// writes do not happen if aborted/failed. This may have some
// performance benefits, but it'll be more difficult to get right.
anteCtx, msCache = app.cacheTxContext(ctx, txBytes, mode)
newCtx, result, abort := app.anteHandler(anteCtx, tx, (mode == runTxModeSimulate))
2018-02-28 19:17:48 -08:00
if abort {
return result
2018-02-28 19:17:48 -08:00
}
if !newCtx.IsZero() {
ctx = newCtx
}
msCache.Write()
gasWanted = result.GasWanted
2018-01-26 05:11:01 -08:00
}
if mode == runTxModeSimulate {
result = app.runMsgs(ctx, msgs, mode)
result.GasWanted = gasWanted
return
}
// Create a new context based off of the existing context with a cache wrapped
// multi-store in case message processing fails.
runMsgCtx, msCache := app.cacheTxContext(ctx, txBytes, mode)
result = app.runMsgs(runMsgCtx, msgs, mode)
result.GasWanted = gasWanted
// only update state if all messages pass
if result.IsOK() {
2018-01-26 05:11:01 -08:00
msCache.Write()
}
return
}
// EndBlock implements the ABCI application interface.
func (app *BaseApp) EndBlock(req abci.RequestEndBlock) (res abci.ResponseEndBlock) {
if app.deliverState.ms.TracingEnabled() {
app.deliverState.ms = app.deliverState.ms.ResetTraceContext().(sdk.CacheMultiStore)
}
if app.endBlocker != nil {
res = app.endBlocker(app.deliverState.ctx, req)
}
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) {
header := app.deliverState.ctx.BlockHeader()
/*
// Write the latest Header to the store
headerBytes, err := proto.Marshal(&header)
if err != nil {
panic(err)
}
app.db.SetSync(dbHeaderKey, headerBytes)
*/
// Write the Deliver state and commit the MultiStore
app.deliverState.ms.Write()
2018-01-26 04:19:33 -08:00
commitID := app.cms.Commit()
Merge PR #1119: Unbonding, Redelegation * stake/fees spec updates * staking overview.md revisions, moving files * docs reorganization * staking spec state revisions * transaction stake updates * complete staking spec update * WIP adding unbonding/redelegation commands * added msg types for unbonding, redelegation * stake sub-package reorg * working stake reorg * modify lcd tests to not use hardcoded json strings * add description update * index keys * key managment for unbonding redelegation complete * update stake errors * completed handleMsgCompleteUnbonding fn * updated to use begin/complete unbonding/redelegation * fix token shares bug * develop docs into unbonding * got non-tests compiling after merge develop * working fixing tests * PrivlegedKeeper -> PrivilegedKeeper * tests compile * fix some tests * fixing tests * remove PrivilegedKeeper * get unbonding bug * only rpc sig verification failed tests now * move percent unbonding/redelegation to the CLI and out of handler logic * remove min unbonding height * add lcd txs * add pool sanity checks, fix a buncha tests * fix ante. set lcd log to debug (#1322) * redelegation tests, adding query functionality for bonds * add self-delegations at genesis ref #1165 * PR comments (mostly) addressed * cleanup, added Query LCD functionality * test cleanup/fixes * fix governance test * SlashValidatorSet -> ValidatorSet * changelog * stake lcd fix * x/auth: fix chainID in ante * fix lcd test * fix lint, update lint make command for spelling * lowercase error string * don't expose coinkeeper in staking * remove a few duplicate lines in changelog * chain_id in stake lcd tests * added transient redelegation * 'transient' => 'transitive' * Re-add nolint instruction * Fix tiny linter error
2018-06-26 19:00:12 -07:00
// TODO: this is missing a module identifier and dumps byte array
app.Logger.Debug("Commit synced",
"commit", commitID,
)
// Reset the Check state to the latest committed
// NOTE: safe because Tendermint holds a lock on the mempool for Commit.
// Use the header from this latest block.
app.setCheckState(header)
2018-04-10 20:51:09 -07:00
// Empty the Deliver state
app.deliverState = nil
2017-12-26 17:04:48 -08:00
return abci.ResponseCommit{
Data: commitID.Hash,
}
2017-12-01 09:10:17 -08:00
}