tendermint/state/execution.go

315 lines
9.5 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"
crypto "github.com/tendermint/go-crypto"
2015-12-01 20:12:01 -08:00
"github.com/tendermint/tendermint/proxy"
2017-04-18 16:29:02 -07:00
"github.com/tendermint/tendermint/state/txindex"
2015-04-01 17:30:16 -07:00
"github.com/tendermint/tendermint/types"
cmn "github.com/tendermint/tmlibs/common"
2017-05-02 00:53:32 -07:00
"github.com/tendermint/tmlibs/log"
)
//--------------------------------------------------
// Execute the block
// ValExecBlock executes the block, but does NOT mutate State.
// + validates the block
// + executes block.Txs on the proxyAppConn
func (s *State) ValExecBlock(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block) (*ABCIResponses, 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
// Execute the block txs
2017-05-02 00:53:32 -07:00
abciResponses, err := execBlockOnProxyApp(eventCache, proxyAppConn, block, s.logger)
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
}
return abciResponses, 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.
2017-05-02 00:53:32 -07:00
func execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block, logger log.Logger) (*ABCIResponses, error) {
var validTxs, invalidTxs = 0, 0
2015-12-01 20:12:01 -08:00
txIndex := 0
abciResponses := NewABCIResponses(block)
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 {
2017-05-02 00:53:32 -07:00
logger.Debug("Invalid tx", "code", txResult.Code, "log", txResult.Log)
invalidTxs++
txError = txResult.Code.String()
}
abciResponses.DeliverTx[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(abci.RequestBeginBlock{
block.Hash(),
types.TM2PB.Header(block.Header),
})
2016-11-03 16:51:22 -07:00
if err != nil {
logger.Error("Error in proxyAppConn.BeginBlock", "err", err)
return nil, err
2016-11-03 16:51:22 -07:00
}
2016-03-05 20:57:36 -08:00
// Run txs of block
for _, tx := range block.Txs {
2017-01-12 12:55:03 -08:00
proxyAppConn.DeliverTxAsync(tx)
if err := proxyAppConn.Error(); err != nil {
return nil, err
2015-12-01 20:12:01 -08:00
}
}
2016-03-05 20:57:36 -08:00
// End block
abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(uint64(block.Height))
2016-03-05 20:57:36 -08:00
if err != nil {
logger.Error("Error in proxyAppConn.EndBlock", "err", err)
return nil, err
2016-03-05 20:57:36 -08:00
}
2016-09-11 12:32:33 -07:00
valDiff := abciResponses.EndBlock.Diffs
2017-06-13 23:41:36 -07:00
logger.Info("Executed block", "height", block.Height, "validTxs", validTxs, "invalidTxs", invalidTxs)
if len(valDiff) > 0 {
2017-05-02 00:53:32 -07:00
logger.Info("Update to validator set", "updates", abci.ValidatorsString(valDiff))
2016-11-22 15:55:42 -08:00
}
return abciResponses, 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(cmn.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(cmn.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(cmn.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(cmn.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) *cmn.BitArray {
signed := cmn.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
2017-08-21 13:12:07 -07:00
// ValidateBlock validates the block against the state.
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(cmn.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 validates & executes the block, updates state w/ ABCI responses,
// then commits and updates the mempool atomically, then saves state.
// Transaction results are optionally indexed.
2017-08-21 13:12:07 -07:00
// ApplyBlock validates the block against the state, executes it against the app,
// commits it, and saves the block and state. It's the only function that needs to be called
// from outside this package to process and commit an entire block.
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 {
abciResponses, err := s.ValExecBlock(eventCache, proxyAppConn, block)
if err != nil {
return fmt.Errorf("Exec failed for application: %v", err)
}
fail.Fail() // XXX
// index txs. This could run in the background
s.indexTxs(abciResponses)
// save the results before we commit
s.SaveABCIResponses(abciResponses)
fail.Fail() // XXX
// now update the block and validators
s.SetBlockAndValidators(block.Header, partsHeader, abciResponses)
// lock mempool, commit state, update mempoool
err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
if err != nil {
return fmt.Errorf("Commit failed for application: %v", err)
}
fail.Fail() // XXX
2017-09-04 15:27:04 -07:00
// save the state and the validators
s.Save()
return nil
}
2016-08-23 18:44:07 -07:00
2017-08-21 13:12:07 -07:00
// CommitStateUpdateMempool locks the mempool, runs the ABCI Commit message, and updates the mempool.
// The 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() {
s.logger.Error("Error in proxyAppConn.CommitSync", "err", res)
2016-08-24 21:18:03 -07:00
return res
}
if res.Log != "" {
2017-05-02 00:53:32 -07:00
s.logger.Debug("Commit.Log: " + res.Log)
2016-08-24 21:18:03 -07:00
}
2017-05-26 08:57:41 -07:00
s.logger.Info("Committed state", "height", block.Height, "txs", block.NumTxs, "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
}
func (s *State) indexTxs(abciResponses *ABCIResponses) {
// save the tx results using the TxIndexer
// NOTE: these may be overwriting, but the values should be the same.
2017-04-18 18:35:00 -07:00
batch := txindex.NewBatch(len(abciResponses.DeliverTx))
for i, d := range abciResponses.DeliverTx {
tx := abciResponses.txs[i]
2017-04-18 18:35:00 -07:00
batch.Add(types.TxResult{
Height: uint64(abciResponses.Height),
Index: uint32(i),
Tx: tx,
Result: *d,
})
}
2017-04-18 18:35:00 -07:00
s.TxIndexer.AddBatch(batch)
}
2017-08-21 13:12:07 -07:00
// ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
// It returns the application root hash (result of abci.Commit).
2017-05-02 00:53:32 -07:00
func ExecCommitBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block, logger log.Logger) ([]byte, error) {
var eventCache types.Fireable // nil
2017-05-02 00:53:32 -07:00
_, err := execBlockOnProxyApp(eventCache, appConnConsensus, block, logger)
if err != nil {
2017-05-02 00:53:32 -07:00
logger.Error("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() {
logger.Error("Error in proxyAppConn.CommitSync", "err", res)
return nil, res
}
if res.Log != "" {
2017-05-02 00:53:32 -07:00
logger.Info("Commit.Log: " + res.Log)
}
return res.Data, nil
}