You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

564 lines
19 KiB

7 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
6 years ago
6 years ago
8 years ago
7 years ago
  1. package state
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. abci "github.com/tendermint/tendermint/abci/types"
  7. dbm "github.com/tendermint/tendermint/libs/db"
  8. "github.com/tendermint/tendermint/libs/fail"
  9. "github.com/tendermint/tendermint/libs/log"
  10. "github.com/tendermint/tendermint/proxy"
  11. "github.com/tendermint/tendermint/types"
  12. )
  13. //-----------------------------------------------------------------------------
  14. // BlockExecutor handles block execution and state updates.
  15. // It exposes ApplyBlock(), which validates & executes the block, updates state w/ ABCI responses,
  16. // then commits and updates the mempool atomically, then saves state.
  17. // BlockExecutor provides the context and accessories for properly executing a block.
  18. type BlockExecutor struct {
  19. // save state, validators, consensus params, abci responses here
  20. db dbm.DB
  21. // execute the app against this
  22. proxyApp proxy.AppConnConsensus
  23. // events
  24. eventBus types.BlockEventPublisher
  25. // manage the mempool lock during commit
  26. // and update both with block results after commit.
  27. mempool Mempool
  28. evpool EvidencePool
  29. logger log.Logger
  30. metrics *Metrics
  31. }
  32. type BlockExecutorOption func(executor *BlockExecutor)
  33. func BlockExecutorWithMetrics(metrics *Metrics) BlockExecutorOption {
  34. return func(blockExec *BlockExecutor) {
  35. blockExec.metrics = metrics
  36. }
  37. }
  38. // NewBlockExecutor returns a new BlockExecutor with a NopEventBus.
  39. // Call SetEventBus to provide one.
  40. func NewBlockExecutor(db dbm.DB, logger log.Logger, proxyApp proxy.AppConnConsensus, mempool Mempool, evpool EvidencePool, options ...BlockExecutorOption) *BlockExecutor {
  41. res := &BlockExecutor{
  42. db: db,
  43. proxyApp: proxyApp,
  44. eventBus: types.NopEventBus{},
  45. mempool: mempool,
  46. evpool: evpool,
  47. logger: logger,
  48. metrics: NopMetrics(),
  49. }
  50. for _, option := range options {
  51. option(res)
  52. }
  53. return res
  54. }
  55. // SetEventBus - sets the event bus for publishing block related events.
  56. // If not called, it defaults to types.NopEventBus.
  57. func (blockExec *BlockExecutor) SetEventBus(eventBus types.BlockEventPublisher) {
  58. blockExec.eventBus = eventBus
  59. }
  60. // CreateProposalBlock calls state.MakeBlock with evidence from the evpool
  61. // and txs from the mempool. The max bytes must be big enough to fit the commit.
  62. // Up to 1/10th of the block space is allcoated for maximum sized evidence.
  63. // The rest is given to txs, up to the max gas.
  64. func (blockExec *BlockExecutor) CreateProposalBlock(
  65. height int64,
  66. state State, commit *types.Commit,
  67. proposerAddr []byte,
  68. ) (*types.Block, *types.PartSet) {
  69. maxBytes := state.ConsensusParams.BlockSize.MaxBytes
  70. maxGas := state.ConsensusParams.BlockSize.MaxGas
  71. // Fetch a limited amount of valid evidence
  72. maxNumEvidence, _ := types.MaxEvidencePerBlock(maxBytes)
  73. evidence := blockExec.evpool.PendingEvidence(maxNumEvidence)
  74. // Fetch a limited amount of valid txs
  75. maxDataBytes := types.MaxDataBytes(maxBytes, state.Validators.Size(), len(evidence))
  76. txs := blockExec.mempool.ReapMaxBytesMaxGas(maxDataBytes, maxGas)
  77. return state.MakeBlock(height, txs, commit, evidence, proposerAddr)
  78. }
  79. // ValidateBlock validates the given block against the given state.
  80. // If the block is invalid, it returns an error.
  81. // Validation does not mutate state, but does require historical information from the stateDB,
  82. // ie. to verify evidence from a validator at an old height.
  83. func (blockExec *BlockExecutor) ValidateBlock(state State, block *types.Block) error {
  84. return validateBlock(blockExec.db, state, block)
  85. }
  86. // ApplyBlock validates the block against the state, executes it against the app,
  87. // fires the relevant events, commits the app, and saves the new state and responses.
  88. // It's the only function that needs to be called
  89. // from outside this package to process and commit an entire block.
  90. // It takes a blockID to avoid recomputing the parts hash.
  91. func (blockExec *BlockExecutor) ApplyBlock(state State, blockID types.BlockID, block *types.Block) (State, error) {
  92. if err := blockExec.ValidateBlock(state, block); err != nil {
  93. return state, ErrInvalidBlock(err)
  94. }
  95. startTime := time.Now().UnixNano()
  96. abciResponses, err := execBlockOnProxyApp(blockExec.logger, blockExec.proxyApp, block, state.LastValidators, blockExec.db)
  97. endTime := time.Now().UnixNano()
  98. blockExec.metrics.BlockProcessingTime.Observe(float64(endTime-startTime) / 1000000)
  99. if err != nil {
  100. return state, ErrProxyAppConn(err)
  101. }
  102. fail.Fail() // XXX
  103. // Save the results before we commit.
  104. saveABCIResponses(blockExec.db, block.Height, abciResponses)
  105. fail.Fail() // XXX
  106. // validate the validator updates and convert to tendermint types
  107. abciValUpdates := abciResponses.EndBlock.ValidatorUpdates
  108. err = validateValidatorUpdates(abciValUpdates, state.ConsensusParams.Validator)
  109. if err != nil {
  110. return state, fmt.Errorf("Error in validator updates: %v", err)
  111. }
  112. validatorUpdates, err := types.PB2TM.ValidatorUpdates(abciValUpdates)
  113. if err != nil {
  114. return state, err
  115. }
  116. if len(validatorUpdates) > 0 {
  117. blockExec.logger.Info("Updates to validators", "updates", makeValidatorUpdatesLogString(validatorUpdates))
  118. }
  119. // Update the state with the block and responses.
  120. state, err = updateState(state, blockID, &block.Header, abciResponses, validatorUpdates)
  121. if err != nil {
  122. return state, fmt.Errorf("Commit failed for application: %v", err)
  123. }
  124. // Lock mempool, commit app state, update mempoool.
  125. appHash, err := blockExec.Commit(state, block)
  126. if err != nil {
  127. return state, fmt.Errorf("Commit failed for application: %v", err)
  128. }
  129. // Update evpool with the block and state.
  130. blockExec.evpool.Update(block, state)
  131. fail.Fail() // XXX
  132. // Update the app hash and save the state.
  133. state.AppHash = appHash
  134. SaveState(blockExec.db, state)
  135. fail.Fail() // XXX
  136. // Events are fired after everything else.
  137. // NOTE: if we crash between Commit and Save, events wont be fired during replay
  138. fireEvents(blockExec.logger, blockExec.eventBus, block, abciResponses, validatorUpdates)
  139. return state, nil
  140. }
  141. // Commit locks the mempool, runs the ABCI Commit message, and updates the
  142. // mempool.
  143. // It returns the result of calling abci.Commit (the AppHash), and an error.
  144. // The Mempool must be locked during commit and update because state is
  145. // typically reset on Commit and old txs must be replayed against committed
  146. // state before new txs are run in the mempool, lest they be invalid.
  147. func (blockExec *BlockExecutor) Commit(
  148. state State,
  149. block *types.Block,
  150. ) ([]byte, error) {
  151. blockExec.mempool.Lock()
  152. defer blockExec.mempool.Unlock()
  153. // while mempool is Locked, flush to ensure all async requests have completed
  154. // in the ABCI app before Commit.
  155. err := blockExec.mempool.FlushAppConn()
  156. if err != nil {
  157. blockExec.logger.Error("Client error during mempool.FlushAppConn", "err", err)
  158. return nil, err
  159. }
  160. // Commit block, get hash back
  161. res, err := blockExec.proxyApp.CommitSync()
  162. if err != nil {
  163. blockExec.logger.Error(
  164. "Client error during proxyAppConn.CommitSync",
  165. "err", err,
  166. )
  167. return nil, err
  168. }
  169. // ResponseCommit has no error code - just data
  170. blockExec.logger.Info(
  171. "Committed state",
  172. "height", block.Height,
  173. "txs", block.NumTxs,
  174. "appHash", fmt.Sprintf("%X", res.Data),
  175. )
  176. // Update mempool.
  177. err = blockExec.mempool.Update(
  178. block.Height,
  179. block.Txs,
  180. TxPreCheck(state),
  181. TxPostCheck(state),
  182. )
  183. return res.Data, err
  184. }
  185. //---------------------------------------------------------
  186. // Helper functions for executing blocks and updating state
  187. // Executes block's transactions on proxyAppConn.
  188. // Returns a list of transaction results and updates to the validator set
  189. func execBlockOnProxyApp(
  190. logger log.Logger,
  191. proxyAppConn proxy.AppConnConsensus,
  192. block *types.Block,
  193. lastValSet *types.ValidatorSet,
  194. stateDB dbm.DB,
  195. ) (*ABCIResponses, error) {
  196. var validTxs, invalidTxs = 0, 0
  197. txIndex := 0
  198. abciResponses := NewABCIResponses(block)
  199. // Execute transactions and get hash.
  200. proxyCb := func(req *abci.Request, res *abci.Response) {
  201. switch r := res.Value.(type) {
  202. case *abci.Response_DeliverTx:
  203. // TODO: make use of res.Log
  204. // TODO: make use of this info
  205. // Blocks may include invalid txs.
  206. txRes := r.DeliverTx
  207. if txRes.Code == abci.CodeTypeOK {
  208. validTxs++
  209. } else {
  210. logger.Debug("Invalid tx", "code", txRes.Code, "log", txRes.Log)
  211. invalidTxs++
  212. }
  213. abciResponses.DeliverTx[txIndex] = txRes
  214. txIndex++
  215. }
  216. }
  217. proxyAppConn.SetResponseCallback(proxyCb)
  218. commitInfo, byzVals := getBeginBlockValidatorInfo(block, lastValSet, stateDB)
  219. // Begin block
  220. var err error
  221. abciResponses.BeginBlock, err = proxyAppConn.BeginBlockSync(abci.RequestBeginBlock{
  222. Hash: block.Hash(),
  223. Header: types.TM2PB.Header(&block.Header),
  224. LastCommitInfo: commitInfo,
  225. ByzantineValidators: byzVals,
  226. })
  227. if err != nil {
  228. logger.Error("Error in proxyAppConn.BeginBlock", "err", err)
  229. return nil, err
  230. }
  231. // Run txs of block.
  232. for _, tx := range block.Txs {
  233. proxyAppConn.DeliverTxAsync(tx)
  234. if err := proxyAppConn.Error(); err != nil {
  235. return nil, err
  236. }
  237. }
  238. // End block.
  239. abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(abci.RequestEndBlock{Height: block.Height})
  240. if err != nil {
  241. logger.Error("Error in proxyAppConn.EndBlock", "err", err)
  242. return nil, err
  243. }
  244. logger.Info("Executed block", "height", block.Height, "validTxs", validTxs, "invalidTxs", invalidTxs)
  245. return abciResponses, nil
  246. }
  247. func getBeginBlockValidatorInfo(block *types.Block, lastValSet *types.ValidatorSet, stateDB dbm.DB) (abci.LastCommitInfo, []abci.Evidence) {
  248. // Sanity check that commit length matches validator set size -
  249. // only applies after first block
  250. if block.Height > 1 {
  251. precommitLen := len(block.LastCommit.Precommits)
  252. valSetLen := len(lastValSet.Validators)
  253. if precommitLen != valSetLen {
  254. // sanity check
  255. panic(fmt.Sprintf("precommit length (%d) doesn't match valset length (%d) at height %d\n\n%v\n\n%v",
  256. precommitLen, valSetLen, block.Height, block.LastCommit.Precommits, lastValSet.Validators))
  257. }
  258. }
  259. // Collect the vote info (list of validators and whether or not they signed).
  260. voteInfos := make([]abci.VoteInfo, len(lastValSet.Validators))
  261. for i, val := range lastValSet.Validators {
  262. var vote *types.CommitSig
  263. if i < len(block.LastCommit.Precommits) {
  264. vote = block.LastCommit.Precommits[i]
  265. }
  266. voteInfo := abci.VoteInfo{
  267. Validator: types.TM2PB.Validator(val),
  268. SignedLastBlock: vote != nil,
  269. }
  270. voteInfos[i] = voteInfo
  271. }
  272. commitInfo := abci.LastCommitInfo{
  273. Round: int32(block.LastCommit.Round()),
  274. Votes: voteInfos,
  275. }
  276. byzVals := make([]abci.Evidence, len(block.Evidence.Evidence))
  277. for i, ev := range block.Evidence.Evidence {
  278. // We need the validator set. We already did this in validateBlock.
  279. // TODO: Should we instead cache the valset in the evidence itself and add
  280. // `SetValidatorSet()` and `ToABCI` methods ?
  281. valset, err := LoadValidators(stateDB, ev.Height())
  282. if err != nil {
  283. panic(err) // shouldn't happen
  284. }
  285. byzVals[i] = types.TM2PB.Evidence(ev, valset, block.Time)
  286. }
  287. return commitInfo, byzVals
  288. }
  289. func validateValidatorUpdates(abciUpdates []abci.ValidatorUpdate,
  290. params types.ValidatorParams) error {
  291. for _, valUpdate := range abciUpdates {
  292. if valUpdate.GetPower() < 0 {
  293. return fmt.Errorf("Voting power can't be negative %v", valUpdate)
  294. } else if valUpdate.GetPower() == 0 {
  295. // continue, since this is deleting the validator, and thus there is no
  296. // pubkey to check
  297. continue
  298. }
  299. // Check if validator's pubkey matches an ABCI type in the consensus params
  300. thisKeyType := valUpdate.PubKey.Type
  301. if !params.IsValidPubkeyType(thisKeyType) {
  302. return fmt.Errorf("Validator %v is using pubkey %s, which is unsupported for consensus",
  303. valUpdate, thisKeyType)
  304. }
  305. }
  306. return nil
  307. }
  308. // If more or equal than 1/3 of total voting power changed in one block, then
  309. // a light client could never prove the transition externally. See
  310. // ./lite/doc.go for details on how a light client tracks validators.
  311. func updateValidators(currentSet *types.ValidatorSet, updates []*types.Validator) error {
  312. for _, valUpdate := range updates {
  313. // should already have been checked
  314. if valUpdate.VotingPower < 0 {
  315. return fmt.Errorf("Voting power can't be negative %v", valUpdate)
  316. }
  317. address := valUpdate.Address
  318. _, val := currentSet.GetByAddress(address)
  319. // valUpdate.VotingPower is ensured to be non-negative in validation method
  320. if valUpdate.VotingPower == 0 { // remove val
  321. _, removed := currentSet.Remove(address)
  322. if !removed {
  323. return fmt.Errorf("Failed to remove validator %X", address)
  324. }
  325. } else if val == nil { // add val
  326. // make sure we do not exceed MaxTotalVotingPower by adding this validator:
  327. totalVotingPower := currentSet.TotalVotingPower()
  328. updatedVotingPower := valUpdate.VotingPower + totalVotingPower
  329. overflow := updatedVotingPower > types.MaxTotalVotingPower || updatedVotingPower < 0
  330. if overflow {
  331. return fmt.Errorf(
  332. "Failed to add new validator %v. Adding it would exceed max allowed total voting power %v",
  333. valUpdate,
  334. types.MaxTotalVotingPower)
  335. }
  336. // TODO: issue #1558 update spec according to the following:
  337. // Set ProposerPriority to -C*totalVotingPower (with C ~= 1.125) to make sure validators can't
  338. // unbond/rebond to reset their (potentially previously negative) ProposerPriority to zero.
  339. //
  340. // Contract: totalVotingPower < MaxTotalVotingPower to ensure ProposerPriority does
  341. // not exceed the bounds of int64.
  342. //
  343. // Compute ProposerPriority = -1.125*totalVotingPower == -(totalVotingPower + (totalVotingPower >> 3)).
  344. valUpdate.ProposerPriority = -(totalVotingPower + (totalVotingPower >> 3))
  345. added := currentSet.Add(valUpdate)
  346. if !added {
  347. return fmt.Errorf("Failed to add new validator %v", valUpdate)
  348. }
  349. } else { // update val
  350. // make sure we do not exceed MaxTotalVotingPower by updating this validator:
  351. totalVotingPower := currentSet.TotalVotingPower()
  352. curVotingPower := val.VotingPower
  353. updatedVotingPower := totalVotingPower - curVotingPower + valUpdate.VotingPower
  354. overflow := updatedVotingPower > types.MaxTotalVotingPower || updatedVotingPower < 0
  355. if overflow {
  356. return fmt.Errorf(
  357. "Failed to update existing validator %v. Updating it would exceed max allowed total voting power %v",
  358. valUpdate,
  359. types.MaxTotalVotingPower)
  360. }
  361. updated := currentSet.Update(valUpdate)
  362. if !updated {
  363. return fmt.Errorf("Failed to update validator %X to %v", address, valUpdate)
  364. }
  365. }
  366. }
  367. return nil
  368. }
  369. // updateState returns a new State updated according to the header and responses.
  370. func updateState(
  371. state State,
  372. blockID types.BlockID,
  373. header *types.Header,
  374. abciResponses *ABCIResponses,
  375. validatorUpdates []*types.Validator,
  376. ) (State, error) {
  377. // Copy the valset so we can apply changes from EndBlock
  378. // and update s.LastValidators and s.Validators.
  379. nValSet := state.NextValidators.Copy()
  380. // Update the validator set with the latest abciResponses.
  381. lastHeightValsChanged := state.LastHeightValidatorsChanged
  382. if len(validatorUpdates) > 0 {
  383. err := updateValidators(nValSet, validatorUpdates)
  384. if err != nil {
  385. return state, fmt.Errorf("Error changing validator set: %v", err)
  386. }
  387. // Change results from this height but only applies to the next next height.
  388. lastHeightValsChanged = header.Height + 1 + 1
  389. }
  390. // Update validator proposer priority and set state variables.
  391. nValSet.IncrementProposerPriority(1)
  392. // Update the params with the latest abciResponses.
  393. nextParams := state.ConsensusParams
  394. lastHeightParamsChanged := state.LastHeightConsensusParamsChanged
  395. if abciResponses.EndBlock.ConsensusParamUpdates != nil {
  396. // NOTE: must not mutate s.ConsensusParams
  397. nextParams = state.ConsensusParams.Update(abciResponses.EndBlock.ConsensusParamUpdates)
  398. err := nextParams.Validate()
  399. if err != nil {
  400. return state, fmt.Errorf("Error updating consensus params: %v", err)
  401. }
  402. // Change results from this height but only applies to the next height.
  403. lastHeightParamsChanged = header.Height + 1
  404. }
  405. // TODO: allow app to upgrade version
  406. nextVersion := state.Version
  407. // NOTE: the AppHash has not been populated.
  408. // It will be filled on state.Save.
  409. return State{
  410. Version: nextVersion,
  411. ChainID: state.ChainID,
  412. LastBlockHeight: header.Height,
  413. LastBlockTotalTx: state.LastBlockTotalTx + header.NumTxs,
  414. LastBlockID: blockID,
  415. LastBlockTime: header.Time,
  416. NextValidators: nValSet,
  417. Validators: state.NextValidators.Copy(),
  418. LastValidators: state.Validators.Copy(),
  419. LastHeightValidatorsChanged: lastHeightValsChanged,
  420. ConsensusParams: nextParams,
  421. LastHeightConsensusParamsChanged: lastHeightParamsChanged,
  422. LastResultsHash: abciResponses.ResultsHash(),
  423. AppHash: nil,
  424. }, nil
  425. }
  426. // Fire NewBlock, NewBlockHeader.
  427. // Fire TxEvent for every tx.
  428. // NOTE: if Tendermint crashes before commit, some or all of these events may be published again.
  429. func fireEvents(logger log.Logger, eventBus types.BlockEventPublisher, block *types.Block, abciResponses *ABCIResponses, validatorUpdates []*types.Validator) {
  430. eventBus.PublishEventNewBlock(types.EventDataNewBlock{
  431. Block: block,
  432. ResultBeginBlock: *abciResponses.BeginBlock,
  433. ResultEndBlock: *abciResponses.EndBlock,
  434. })
  435. eventBus.PublishEventNewBlockHeader(types.EventDataNewBlockHeader{
  436. Header: block.Header,
  437. ResultBeginBlock: *abciResponses.BeginBlock,
  438. ResultEndBlock: *abciResponses.EndBlock,
  439. })
  440. for i, tx := range block.Data.Txs {
  441. eventBus.PublishEventTx(types.EventDataTx{types.TxResult{
  442. Height: block.Height,
  443. Index: uint32(i),
  444. Tx: tx,
  445. Result: *(abciResponses.DeliverTx[i]),
  446. }})
  447. }
  448. if len(validatorUpdates) > 0 {
  449. eventBus.PublishEventValidatorSetUpdates(
  450. types.EventDataValidatorSetUpdates{ValidatorUpdates: validatorUpdates})
  451. }
  452. }
  453. //----------------------------------------------------------------------------------------------------
  454. // Execute block without state. TODO: eliminate
  455. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  456. // It returns the application root hash (result of abci.Commit).
  457. func ExecCommitBlock(
  458. appConnConsensus proxy.AppConnConsensus,
  459. block *types.Block,
  460. logger log.Logger,
  461. lastValSet *types.ValidatorSet,
  462. stateDB dbm.DB,
  463. ) ([]byte, error) {
  464. _, err := execBlockOnProxyApp(logger, appConnConsensus, block, lastValSet, stateDB)
  465. if err != nil {
  466. logger.Error("Error executing block on proxy app", "height", block.Height, "err", err)
  467. return nil, err
  468. }
  469. // Commit block, get hash back
  470. res, err := appConnConsensus.CommitSync()
  471. if err != nil {
  472. logger.Error("Client error during proxyAppConn.CommitSync", "err", res)
  473. return nil, err
  474. }
  475. // ResponseCommit has no error or log, just data
  476. return res.Data, nil
  477. }
  478. // Make pretty string for validatorUpdates logging
  479. func makeValidatorUpdatesLogString(vals []*types.Validator) string {
  480. chunks := make([]string, len(vals))
  481. for i, val := range vals {
  482. chunks[i] = fmt.Sprintf("%s:%d", val.Address, val.VotingPower)
  483. }
  484. return strings.Join(chunks, ",")
  485. }