tendermint/state/execution.go

301 lines
8.8 KiB
Go
Raw Normal View History

package state
import (
"errors"
"fmt"
fail "github.com/ebuchman/fail-test"
2017-02-14 12:33:14 -08:00
abci "github.com/tendermint/abci/types"
. "github.com/tendermint/go-common"
crypto "github.com/tendermint/go-crypto"
2015-12-01 20:12:01 -08:00
"github.com/tendermint/tendermint/proxy"
txindexer "github.com/tendermint/tendermint/state/tx/indexer"
2015-04-01 17:30:16 -07:00
"github.com/tendermint/tendermint/types"
)
// ExecBlock executes the block to mutate State.
// + validates the block
// + executes block.Txs on the proxyAppConn
// + updates validator sets
// + returns block.Txs results
func (s *State) ExecBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block, blockPartsHeader types.PartSetHeader) ([]*types.TxResult, 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 nil, 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
txResults, 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 nil, ErrProxyAppConn(err)
2015-12-01 20:12:01 -08:00
}
2016-11-19 16:32:35 -08:00
// update the validator set
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
fail.Fail() // XXX
return txResults, nil
}
// Executes block's transactions on proxyAppConn.
// Returns a list of transaction results and updates to the validator set
// TODO: Generate a bitmap or otherwise store tx validity in state.
func execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block) ([]*types.TxResult, []*abci.Validator, error) {
var validTxs, invalidTxs = 0, 0
2015-12-01 20:12:01 -08:00
txResults := make([]*types.TxResult, len(block.Txs))
txIndex := 0
2015-12-01 20:12:01 -08:00
// Execute transactions and get hash
2017-01-12 12:53:32 -08:00
proxyCb := func(req *abci.Request, res *abci.Response) {
2016-05-14 09:33:27 -07:00
switch r := res.Value.(type) {
2017-01-12 12:55:03 -08:00
case *abci.Response_DeliverTx:
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.
2017-01-12 12:55:03 -08:00
// reqDeliverTx := req.(abci.RequestDeliverTx)
txError := ""
txResult := r.DeliverTx
if txResult.Code == abci.CodeType_OK {
validTxs++
} else {
log.Debug("Invalid tx", "code", txResult.Code, "log", txResult.Log)
invalidTxs++
txError = txResult.Code.String()
}
txResults[txIndex] = &types.TxResult{uint64(block.Height), uint32(txIndex), *txResult}
txIndex++
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{
Height: block.Height,
Tx: types.Tx(req.GetDeliverTx().Tx),
Data: txResult.Data,
Code: txResult.Code,
Log: txResult.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 nil, 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
2017-01-12 12:55:03 -08:00
proxyAppConn.DeliverTxAsync(tx)
if err := proxyAppConn.Error(); err != nil {
return nil, 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
respEndBlock, 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 nil, nil, err
2016-03-05 20:57:36 -08:00
}
2016-09-11 12:32:33 -07:00
fail.Fail() // XXX
2016-11-22 15:55:42 -08:00
log.Info("Executed block", "height", block.Height, "valid txs", validTxs, "invalid txs", invalidTxs)
if len(respEndBlock.Diffs) > 0 {
2017-01-12 12:53:32 -08:00
log.Info("Update to validator set", "updates", abci.ValidatorsString(respEndBlock.Diffs))
2016-11-22 15:55:42 -08:00
}
return txResults, respEndBlock.Diffs, nil
2016-11-19 16:32:35 -08:00
}
2017-01-12 12:53:32 -08:00
func updateValidators(validators *types.ValidatorSet, changedValidators []*abci.Validator) error {
2016-11-19 16:32:35 -08:00
// TODO: prevent change of 1/3+ at once
for _, v := range changedValidators {
pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
if err != nil {
return 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 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 errors.New(Fmt("Failed to add new validator %X with voting power %d", address, power))
2016-11-19 16:32:35 -08:00
}
} else if v.Power == 0 {
// remove val
_, removed := validators.Remove(address)
if !removed {
return errors.New(Fmt("Failed to remove validator %X)"))
2016-11-19 16:32:35 -08:00
}
} else {
// update val
val.VotingPower = power
updated := validators.Update(val)
if !updated {
return errors.New(Fmt("Failed to update validator %X with voting power %d", address, power))
2016-11-19 16:32:35 -08:00
}
}
}
return 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 {
2016-11-22 15:55:42 -08:00
if precommit != nil {
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, optionally indexing transaction results.
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 types.Mempool) error {
txResults, err := s.ExecBlock(eventCache, proxyAppConn, block, partsHeader)
if err != nil {
return fmt.Errorf("Exec failed for application: %v", err)
}
// lock mempool, commit state, update mempoool
err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
if err != nil {
return fmt.Errorf("Commit failed for application: %v", err)
}
batch := txindexer.NewBatch()
for i, r := range txResults {
2017-04-12 15:18:17 -07:00
tx := block.Txs[i]
batch.Index(tx.Hash(), *r)
}
s.TxIndexer.Batch(batch)
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 types.Mempool) error {
2016-08-24 21:18:03 -07:00
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)
}
2017-02-20 13:24:35 -08:00
log.Info("Committed state", "hash", res.Data)
2016-08-24 21:18:03 -07:00
// Set the state's new AppHash
s.AppHash = res.Data
// Update mempool.
mempool.Update(block.Height, block.Txs)
return nil
}
2017-02-18 19:15:59 -08:00
// Apply and commit a block, but without all the state validation.
// Returns the application root hash (result of abci.Commit)
2017-02-20 16:52:36 -08:00
func ApplyBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block) ([]byte, error) {
var eventCache types.Fireable // nil
_, _, err := execBlockOnProxyApp(eventCache, appConnConsensus, block)
if err != nil {
log.Warn("Error executing block on proxy app", "height", block.Height, "err", err)
return nil, err
}
// Commit block, get hash back
res := appConnConsensus.CommitSync()
if res.IsErr() {
log.Warn("Error in proxyAppConn.CommitSync", "error", res)
return nil, res
}
if res.Log != "" {
log.Info("Commit.Log: " + res.Log)
}
return res.Data, nil
}