tendermint/state/execution.go

458 lines
14 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"
cfg "github.com/tendermint/go-config"
2016-11-19 16:32:35 -08:00
"github.com/tendermint/go-crypto"
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
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.
2016-11-19 16:32:35 -08:00
if err := s.validateBlock(block); err != nil {
return ErrInvalidBlock(err)
}
2015-12-01 20:12:01 -08:00
2016-11-19 16:32:35 -08:00
// compute bitarray of validators that signed
2016-11-16 17:58:53 -08:00
signed := commitBitArrayFromBlock(block)
2016-11-19 16:32:35 -08:00
_ = signed // TODO send on begin block
2016-11-16 17:58:53 -08:00
2016-11-19 16:32:35 -08:00
// copy the valset
valSet := s.Validators.Copy()
2015-12-01 20:12:01 -08:00
nextValSet := valSet.Copy()
// Execute the block txs
2016-11-19 16:32:35 -08:00
changedValidators, err := 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
}
2016-11-19 16:32:35 -08:00
// update the validator set
s.valAddedOrRemoved, err = updateValidators(nextValSet, changedValidators)
if err != nil {
2016-11-19 16:32:35 -08:00
log.Warn("Error changing validator set", "error", err)
// TODO: err or carry on?
}
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.
2016-11-19 16:32:35 -08:00
// Returns a list of updates to the validator set
// TODO: Generate a bitmap or otherwise store tx validity in state.
2016-11-19 16:32:35 -08:00
func execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block) ([]*tmsp.Validator, 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)
2016-11-19 16:32:35 -08:00
return nil, err
2016-11-03 16:51:22 -07:00
}
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 {
2016-11-19 16:32:35 -08:00
return nil, err
2015-12-01 20:12:01 -08:00
}
}
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)
2016-11-19 16:32:35 -08:00
return nil, err
2016-03-05 20:57:36 -08:00
}
2016-09-11 12:32:33 -07:00
fail.Fail() // XXX
2016-01-12 16:30:31 -08:00
log.Info(Fmt("ExecBlock got %v valid txs and %v invalid txs", validTxs, invalidTxs))
2016-11-19 16:32:35 -08:00
return changedValidators, nil
}
func updateValidators(validators *types.ValidatorSet, changedValidators []*tmsp.Validator) (bool, error) {
2016-11-19 16:32:35 -08:00
// TODO: prevent change of 1/3+ at once
var addedOrRemoved bool
2016-11-19 16:32:35 -08:00
for _, v := range changedValidators {
pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
if err != nil {
return false, err
2016-11-19 16:32:35 -08:00
}
address := pubkey.Address()
power := int64(v.Power)
// mind the overflow from uint64
if power < 0 {
return false, errors.New(Fmt("Power (%d) overflows int64", v.Power))
2016-11-19 16:32:35 -08:00
}
_, val := validators.GetByAddress(address)
if val == nil {
// add val
added := validators.Add(types.NewValidator(pubkey, power))
if !added {
return false, errors.New(Fmt("Failed to add new validator %X with voting power %d", address, power))
2016-11-19 16:32:35 -08:00
}
addedOrRemoved = true
2016-11-19 16:32:35 -08:00
} else if v.Power == 0 {
// remove val
_, removed := validators.Remove(address)
if !removed {
return false, errors.New(Fmt("Failed to remove validator %X)"))
2016-11-19 16:32:35 -08:00
}
addedOrRemoved = true
2016-11-19 16:32:35 -08:00
} else {
// update val
val.VotingPower = power
updated := validators.Update(val)
if !updated {
return false, errors.New(Fmt("Failed to update validator %X with voting power %d", address, power))
2016-11-19 16:32:35 -08:00
}
}
}
return addedOrRemoved, nil
2015-12-01 20:12:01 -08:00
}
2016-11-16 17:58:53 -08:00
// return a bit array of validators that signed the last commit
// NOTE: assumes commits have already been authenticated
func commitBitArrayFromBlock(block *types.Block) *BitArray {
signed := NewBitArray(len(block.LastCommit.Precommits))
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
}
2016-11-16 17:58:53 -08:00
signed.SetIndex(i, true) // val_.LastCommitHeight = block.Height - 1
}
2016-11-16 17:58:53 -08:00
return signed
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
2016-11-03 17:38:09 -07:00
func (s *State) ApplyBlock(eventCache types.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) {}
//----------------------------------------------------------------
// Handshake with app to sync to latest state of core by replaying blocks
// TODO: Should we move blockchain/store.go to its own package?
type BlockStore interface {
Height() int
LoadBlock(height int) *types.Block
}
type Handshaker struct {
config cfg.Config
state *State
store BlockStore
nBlocks int // number of blocks applied to the state
2016-09-11 12:32:33 -07:00
}
func NewHandshaker(config cfg.Config, state *State, store BlockStore) *Handshaker {
return &Handshaker{config, state, store, 0}
2016-09-11 12:32:33 -07:00
}
// TODO: retry the handshake once if it fails the first time
// ... let Info take an argument determining its behaviour
func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error {
// handshake is done via info request on the query conn
res, tmspInfo, blockInfo, configInfo := proxyApp.Query().InfoSync()
if res.IsErr() {
return errors.New(Fmt("Error calling Info. Code: %v; Data: %X; Log: %s", res.Code, res.Data, res.Log))
}
if blockInfo == nil {
log.Warn("blockInfo is nil, aborting handshake")
return nil
}
log.Notice("TMSP Handshake", "height", blockInfo.BlockHeight, "block_hash", blockInfo.BlockHash, "app_hash", blockInfo.AppHash)
blockHeight := int(blockInfo.BlockHeight) // safe, should be an int32
blockHash := blockInfo.BlockHash
appHash := blockInfo.AppHash
if tmspInfo != nil {
// TODO: check tmsp version (or do this in the tmspcli?)
_ = tmspInfo
}
// last block (nil if we starting from 0)
var header *types.Header
var partsHeader types.PartSetHeader
// replay all blocks after blockHeight
// if blockHeight == 0, we will replay everything
if blockHeight != 0 {
block := h.store.LoadBlock(blockHeight)
if block == nil {
return ErrUnknownBlock{blockHeight}
}
// check block hash
if !bytes.Equal(block.Hash(), blockHash) {
return ErrBlockHashMismatch{block.Hash(), blockHash, blockHeight}
}
// NOTE: app hash should be in the next block ...
// check app hash
/*if !bytes.Equal(block.Header.AppHash, appHash) {
return fmt.Errorf("Handshake error. App hash at height %d does not match. Got %X, expected %X", blockHeight, appHash, block.Header.AppHash)
}*/
header = block.Header
partsHeader = block.MakePartSet(h.config.GetInt("block_part_size")).Header()
}
if configInfo != nil {
// TODO: set config info
_ = configInfo
}
// replay blocks up to the latest in the blockstore
err := h.ReplayBlocks(appHash, header, partsHeader, proxyApp.Consensus())
if err != nil {
return errors.New(Fmt("Error on replay: %v", err))
}
// TODO: (on restart) replay mempool
return nil
2016-08-24 21:18:03 -07:00
}
// Replay all blocks after blockHeight and ensure the result matches the current state.
func (h *Handshaker) ReplayBlocks(appHash []byte, header *types.Header, partsHeader types.PartSetHeader,
appConnConsensus proxy.AppConnConsensus) error {
2016-08-23 18:44:07 -07:00
// 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
2016-11-19 16:59:56 -08:00
var appBlockHeight int
if header != nil {
appBlockHeight = header.Height
2016-08-23 18:44:07 -07:00
}
coreBlockHeight := h.store.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 h.state.Stale {
h.state.Stale = false
h.state.AppHash = appHash
}
2016-11-19 16:59:56 -08:00
return nil
2016-09-11 12:32:33 -07:00
} else if h.state.LastBlockHeight == appBlockHeight {
2016-09-11 12:32:33 -07:00
// 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
block := h.store.LoadBlock(coreBlockHeight)
if !bytes.Equal(block.Header.AppHash, appHash) {
return ErrLastStateMismatch{coreBlockHeight, block.Header.AppHash, appHash}
2016-09-11 12:32:33 -07:00
}
2016-11-19 16:59:56 -08:00
h.nBlocks += 1
var eventCache types.Fireable // nil
// replay the block against the actual tendermint state
return h.state.ApplyBlock(eventCache, appConnConsensus, block, block.MakePartSet(h.config.GetInt("block_part_size")).Header(), mockMempool{})
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
2016-11-19 16:59:56 -08:00
var eventCache types.Fireable // nil
var appHash []byte
for i := appBlockHeight + 1; i <= coreBlockHeight; i++ {
2016-11-19 16:59:56 -08:00
h.nBlocks += 1
block := h.store.LoadBlock(i)
_, err := execBlockOnProxyApp(eventCache, appConnConsensus, block)
if err != nil {
// ...
}
// Commit block, get hash back
res := appConnConsensus.CommitSync()
if res.IsErr() {
log.Warn("Error in proxyAppConn.CommitSync", "error", res)
return res
}
if res.Log != "" {
log.Info("Commit.Log: " + res.Log)
}
appHash = res.Data
}
if !bytes.Equal(h.state.AppHash, appHash) {
return errors.New(Fmt("Tendermint state.AppHash does not match AppHash after replay", "expected", h.state.AppHash, "got", appHash))
}
2016-08-24 21:18:03 -07:00
}
2016-11-19 16:59:56 -08:00
return nil // should never happen
2016-08-24 21:18:03 -07:00
}