tendermint/state/execution.go

383 lines
12 KiB
Go
Raw Normal View History

package state
import (
2016-09-11 12:32:33 -07:00
"bytes"
"errors"
2016-09-11 12:32:33 -07:00
"github.com/ebuchman/fail-test"
. "github.com/tendermint/go-common"
2015-12-01 20:12:01 -08:00
"github.com/tendermint/tendermint/proxy"
2015-04-01 17:30:16 -07:00
"github.com/tendermint/tendermint/types"
2015-12-01 20:12:01 -08:00
tmsp "github.com/tendermint/tmsp/types"
)
//--------------------------------------------------
// Execute the block
type (
ErrInvalidBlock error
ErrProxyAppConn error
)
2015-12-01 20:12:01 -08:00
// Execute the block to mutate State.
// Validates block and then executes Data.Txs in the block.
2016-10-09 23:58:13 -07:00
func (s *State) ExecBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block, blockPartsHeader types.PartSetHeader) error {
2015-12-01 20:12:01 -08:00
// Validate the block.
err := s.validateBlock(block)
if err != nil {
return ErrInvalidBlock(err)
}
2015-12-01 20:12:01 -08:00
// Update the validator set
valSet := s.Validators.Copy()
// Update valSet with signatures from block.
updateValidatorsWithBlock(s.LastValidators, valSet, block)
// TODO: Update the validator set (e.g. block.Data.ValidatorUpdates?)
nextValSet := valSet.Copy()
// Execute the block txs
err = s.execBlockOnProxyApp(eventCache, proxyAppConn, block)
2015-12-01 20:12:01 -08:00
if err != nil {
// There was some error in proxyApp
// TODO Report error and wait for proxyApp to be available.
return ErrProxyAppConn(err)
2015-12-01 20:12:01 -08:00
}
// All good!
2016-08-23 18:44:07 -07:00
// Update validator accums and set state variables
2015-12-01 20:12:01 -08:00
nextValSet.IncrementAccum(1)
2016-08-23 18:44:07 -07:00
s.SetBlockAndValidators(block.Header, blockPartsHeader, valSet, nextValSet)
2015-12-01 20:12:01 -08:00
// save state with updated height/blockhash/validators
// but stale apphash, in case we fail between Commit and Save
s.Save()
return nil
}
// Executes block's transactions on proxyAppConn.
// TODO: Generate a bitmap or otherwise store tx validity in state.
2016-10-09 23:58:13 -07:00
func (s *State) execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block) error {
2016-06-27 17:43:09 -07:00
var validTxs, invalidTxs = 0, 0
2015-12-01 20:12:01 -08:00
// Execute transactions and get hash
2016-01-31 08:11:50 -08:00
proxyCb := func(req *tmsp.Request, res *tmsp.Response) {
2016-05-14 09:33:27 -07:00
switch r := res.Value.(type) {
case *tmsp.Response_AppendTx:
2016-01-25 14:34:08 -08:00
// TODO: make use of res.Log
// TODO: make use of this info
// Blocks may include invalid txs.
// reqAppendTx := req.(tmsp.RequestAppendTx)
txError := ""
apTx := r.AppendTx
if apTx.Code == tmsp.CodeType_OK {
validTxs += 1
} else {
2016-05-14 09:33:27 -07:00
log.Debug("Invalid tx", "code", r.AppendTx.Code, "log", r.AppendTx.Log)
invalidTxs += 1
2016-10-09 23:58:13 -07:00
txError = apTx.Code.String()
2015-12-01 20:12:01 -08:00
}
2016-06-27 17:43:09 -07:00
// NOTE: if we count we can access the tx from the block instead of
// pulling it from the req
event := types.EventDataTx{
Tx: req.GetAppendTx().Tx,
Result: apTx.Data,
Code: apTx.Code,
Log: apTx.Log,
Error: txError,
}
2016-10-09 23:58:13 -07:00
types.FireEventTx(eventCache, event)
2015-12-01 20:12:01 -08:00
}
}
proxyAppConn.SetResponseCallback(proxyCb)
2016-11-03 16:51:22 -07:00
// Begin block
err := proxyAppConn.BeginBlockSync(block.Hash(), types.TM2PB.Header(block.Header))
2016-11-03 16:51:22 -07:00
if err != nil {
log.Warn("Error in proxyAppConn.BeginBlock", "error", err)
return err
}
2016-09-11 12:32:33 -07:00
fail.Fail() // XXX
2016-03-05 20:57:36 -08:00
// Run txs of block
for _, tx := range block.Txs {
2016-09-11 12:32:33 -07:00
fail.FailRand(len(block.Txs)) // XXX
proxyAppConn.AppendTxAsync(tx)
if err := proxyAppConn.Error(); err != nil {
2015-12-01 20:12:01 -08:00
return err
}
}
2016-03-05 20:57:36 -08:00
2016-09-11 12:32:33 -07:00
fail.Fail() // XXX
2016-03-05 20:57:36 -08:00
// End block
2016-03-06 18:02:29 -08:00
changedValidators, err := proxyAppConn.EndBlockSync(uint64(block.Height))
2016-03-05 20:57:36 -08:00
if err != nil {
log.Warn("Error in proxyAppConn.EndBlock", "error", err)
return err
}
2016-09-11 12:32:33 -07:00
fail.Fail() // XXX
2016-03-05 20:57:36 -08:00
// TODO: Do something with changedValidators
2016-11-03 17:13:39 -07:00
log.Debug("TODO: Do something with changedValidators", "changedValidators", changedValidators)
2016-03-05 20:57:36 -08:00
2016-01-12 16:30:31 -08:00
log.Info(Fmt("ExecBlock got %v valid txs and %v invalid txs", validTxs, invalidTxs))
2015-12-01 20:12:01 -08:00
return nil
}
// Updates the LastCommitHeight of the validators in valSet, in place.
2016-04-02 09:10:16 -07:00
// Assumes that lastValSet matches the valset of block.LastCommit
2015-12-01 20:12:01 -08:00
// CONTRACT: lastValSet is not mutated.
func updateValidatorsWithBlock(lastValSet *types.ValidatorSet, valSet *types.ValidatorSet, block *types.Block) {
2016-04-02 09:10:16 -07:00
for i, precommit := range block.LastCommit.Precommits {
2015-06-21 19:11:21 -07:00
if precommit == nil {
continue
}
2015-12-01 20:12:01 -08:00
_, val := lastValSet.GetByIndex(i)
if val == nil {
2015-07-19 16:42:52 -07:00
PanicCrisis(Fmt("Failed to fetch validator at index %v", i))
}
2015-12-01 20:12:01 -08:00
if _, val_ := valSet.GetByAddress(val.Address); val_ != nil {
val_.LastCommitHeight = block.Height - 1
2015-12-01 20:12:01 -08:00
updated := valSet.Update(val_)
if !updated {
2015-11-01 11:34:08 -08:00
PanicCrisis("Failed to update validator LastCommitHeight")
}
} else {
2015-12-01 20:12:01 -08:00
// XXX This is not an error if validator was removed.
// But, we don't mutate validators yet so go ahead and panic.
2015-07-19 16:42:52 -07:00
PanicCrisis("Could not find validator")
}
}
2015-05-12 17:40:19 -07:00
}
//-----------------------------------------------------
// Validate block
func (s *State) ValidateBlock(block *types.Block) error {
return s.validateBlock(block)
}
func (s *State) validateBlock(block *types.Block) error {
// Basic block validation.
err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockID, s.LastBlockTime, s.AppHash)
if err != nil {
return err
}
// Validate block LastCommit.
if block.Height == 1 {
if len(block.LastCommit.Precommits) != 0 {
return errors.New("Block at height 1 (first block) should have no LastCommit precommits")
}
} else {
if len(block.LastCommit.Precommits) != s.LastValidators.Size() {
return errors.New(Fmt("Invalid block commit size. Expected %v, got %v",
s.LastValidators.Size(), len(block.LastCommit.Precommits)))
}
err := s.LastValidators.VerifyCommit(
s.ChainID, s.LastBlockID, block.Height-1, block.LastCommit)
if err != nil {
return err
}
}
return nil
2015-12-01 20:12:01 -08:00
}
2016-08-23 18:44:07 -07:00
//-----------------------------------------------------------------------------
// ApplyBlock executes the block, then commits and updates the mempool atomically
// Execute and commit block against app, save block and state
func (s *State) ApplyBlock(eventCache events.Fireable, proxyAppConn proxy.AppConnConsensus,
block *types.Block, partsHeader types.PartSetHeader, mempool Mempool) error {
// Run the block on the State:
// + update validator sets
// + run txs on the proxyAppConn
err := s.ExecBlock(eventCache, proxyAppConn, block, partsHeader)
if err != nil {
return errors.New(Fmt("Exec failed for application: %v", err))
}
// lock mempool, commit state, update mempoool
err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
if err != nil {
return errors.New(Fmt("Commit failed for application: %v", err))
}
return nil
}
2016-08-23 18:44:07 -07:00
2016-08-24 21:18:03 -07:00
// mempool must be locked during commit and update
// because state is typically reset on Commit and old txs must be replayed
// against committed state before new txs are run in the mempool, lest they be invalid
func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, block *types.Block, mempool Mempool) error {
mempool.Lock()
defer mempool.Unlock()
// Commit block, get hash back
res := proxyAppConn.CommitSync()
if res.IsErr() {
log.Warn("Error in proxyAppConn.CommitSync", "error", res)
return res
}
if res.Log != "" {
log.Debug("Commit.Log: " + res.Log)
}
// Set the state's new AppHash
s.AppHash = res.Data
// Update mempool.
mempool.Update(block.Height, block.Txs)
return nil
}
// Updates to the mempool need to be synchronized with committing a block
// so apps can reset their transient state on Commit
type Mempool interface {
Lock()
Unlock()
Update(height int, txs []types.Tx)
}
2016-08-24 21:18:03 -07:00
type mockMempool struct {
}
2016-08-24 21:18:03 -07:00
func (m mockMempool) Lock() {}
func (m mockMempool) Unlock() {}
func (m mockMempool) Update(height int, txs []types.Tx) {}
//----------------------------------------------------------------
// Replay blocks to sync app to latest state of core
2016-09-11 12:32:33 -07:00
type ErrReplay error
type ErrAppBlockHeightTooHigh struct {
coreHeight int
appHeight int
}
func (e ErrAppBlockHeightTooHigh) Error() string {
return Fmt("App block height (%d) is higher than core (%d)", e.appHeight, e.coreHeight)
}
2016-09-11 12:32:33 -07:00
type ErrLastStateMismatch struct {
height int
core []byte
app []byte
}
func (e ErrLastStateMismatch) Error() string {
return Fmt("Latest tendermint block (%d) LastAppHash (%X) does not match app's AppHash (%X)", e.height, e.core, e.app)
}
type ErrStateMismatch struct {
got *State
expected *State
}
func (e ErrStateMismatch) Error() string {
return Fmt("State after replay does not match saved state. Got ----\n%v\nExpected ----\n%v\n", e.got, e.expected)
2016-08-24 21:18:03 -07:00
}
// Replay all blocks after blockHeight and ensure the result matches the current state.
// XXX: blockStore must guarantee to have blocks for height <= blockStore.Height()
func (s *State) ReplayBlocks(appHash []byte, header *types.Header, partsHeader types.PartSetHeader,
2016-08-23 18:44:07 -07:00
appConnConsensus proxy.AppConnConsensus, blockStore proxy.BlockStore) error {
// NOTE/TODO: tendermint may crash after the app commits
// but before it can save the new state root.
// it should save all eg. valset changes before calling Commit.
// then, if tm state is behind app state, the only thing missing can be app hash
// get a fresh state and reset to the apps latest
2016-08-23 18:44:07 -07:00
stateCopy := s.Copy()
if header != nil {
// TODO: put validators in iavl tree so we can set the state with an older validator set
lastVals, nextVals := stateCopy.GetValidators()
stateCopy.SetBlockAndValidators(header, partsHeader, lastVals, nextVals)
stateCopy.Stale = false
stateCopy.AppHash = appHash
2016-08-23 18:44:07 -07:00
}
appBlockHeight := stateCopy.LastBlockHeight
coreBlockHeight := blockStore.Height()
if coreBlockHeight < appBlockHeight {
2016-09-11 12:32:33 -07:00
// if the app is ahead, there's nothing we can do
return ErrAppBlockHeightTooHigh{coreBlockHeight, appBlockHeight}
} else if coreBlockHeight == appBlockHeight {
// if we crashed between Commit and SaveState,
2016-09-11 12:32:33 -07:00
// the state's app hash is stale.
// otherwise we're synced
if s.Stale {
s.Stale = false
s.AppHash = appHash
}
2016-09-11 12:32:33 -07:00
return checkState(s, stateCopy)
} else if s.LastBlockHeight == appBlockHeight {
// core is ahead of app but core's state height is at apps height
// this happens if we crashed after saving the block,
// but before committing it. We should be 1 ahead
if coreBlockHeight != appBlockHeight+1 {
PanicSanity(Fmt("core.state.height == app.height but core.height (%d) > app.height+1 (%d)", coreBlockHeight, appBlockHeight+1))
}
// check that the blocks last apphash is the states apphash
blockMeta := blockStore.LoadBlockMeta(coreBlockHeight)
if !bytes.Equal(blockMeta.Header.AppHash, appHash) {
return ErrLastStateMismatch{coreBlockHeight, blockMeta.Header.AppHash, appHash}
}
// replay the block against the actual tendermint state (not the copy)
return loadApplyBlock(coreBlockHeight, s, blockStore, appConnConsensus)
2016-08-23 18:44:07 -07:00
} else {
2016-09-11 12:32:33 -07:00
// either we're caught up or there's blocks to replay
// replay all blocks starting with appBlockHeight+1
for i := appBlockHeight + 1; i <= coreBlockHeight; i++ {
2016-09-11 12:32:33 -07:00
loadApplyBlock(i, stateCopy, blockStore, appConnConsensus)
}
2016-09-11 12:32:33 -07:00
return checkState(s, stateCopy)
2016-08-23 18:44:07 -07:00
}
2016-09-11 12:32:33 -07:00
}
2016-08-23 18:44:07 -07:00
2016-09-11 12:32:33 -07:00
func checkState(s, stateCopy *State) error {
2016-08-23 18:44:07 -07:00
// The computed state and the previously set state should be identical
if !s.Equals(stateCopy) {
return ErrStateMismatch{stateCopy, s}
2016-08-23 18:44:07 -07:00
}
return nil
}
2016-08-24 21:18:03 -07:00
2016-09-11 12:32:33 -07:00
func loadApplyBlock(blockIndex int, s *State, blockStore proxy.BlockStore, appConnConsensus proxy.AppConnConsensus) error {
blockMeta := blockStore.LoadBlockMeta(blockIndex)
block := blockStore.LoadBlock(blockIndex)
panicOnNilBlock(blockIndex, blockStore.Height(), block, blockMeta) // XXX
var eventCache events.Fireable // nil
return s.ApplyBlock(eventCache, appConnConsensus, block, blockMeta.PartsHeader, mockMempool{})
}
2016-08-24 21:18:03 -07:00
func panicOnNilBlock(height, bsHeight int, block *types.Block, blockMeta *types.BlockMeta) {
if block == nil || blockMeta == nil {
// Sanity?
PanicCrisis(Fmt(`
block/blockMeta is nil for height <= blockStore.Height() (%d <= %d).
Block: %v,
BlockMeta: %v
`, height, bsHeight, block, blockMeta))
}
}