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.

427 lines
14 KiB

8 years ago
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
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
8 years ago
8 years ago
8 years ago
  1. package state
  2. import (
  3. "errors"
  4. "fmt"
  5. fail "github.com/ebuchman/fail-test"
  6. abci "github.com/tendermint/abci/types"
  7. crypto "github.com/tendermint/go-crypto"
  8. "github.com/tendermint/tendermint/proxy"
  9. "github.com/tendermint/tendermint/types"
  10. dbm "github.com/tendermint/tmlibs/db"
  11. "github.com/tendermint/tmlibs/log"
  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. // update these with block results after commit
  26. mempool types.Mempool
  27. evpool types.EvidencePool
  28. logger log.Logger
  29. }
  30. // NewBlockExecutor returns a new BlockExecutor with a NopEventBus.
  31. // Call SetEventBus to provide one.
  32. func NewBlockExecutor(db dbm.DB, logger log.Logger, proxyApp proxy.AppConnConsensus,
  33. mempool types.Mempool, evpool types.EvidencePool) *BlockExecutor {
  34. return &BlockExecutor{
  35. db: db,
  36. proxyApp: proxyApp,
  37. eventBus: types.NopEventBus{},
  38. mempool: mempool,
  39. evpool: evpool,
  40. logger: logger,
  41. }
  42. }
  43. // SetEventBus - sets the event bus for publishing block related events.
  44. // If not called, it defaults to types.NopEventBus.
  45. func (blockExec *BlockExecutor) SetEventBus(eventBus types.BlockEventPublisher) {
  46. blockExec.eventBus = eventBus
  47. }
  48. // ValidateBlock validates the given block against the given state.
  49. // If the block is invalid, it returns an error.
  50. // Validation does not mutate state, but does require historical information from the stateDB,
  51. // ie. to verify evidence from a validator at an old height.
  52. func (blockExec *BlockExecutor) ValidateBlock(s State, block *types.Block) error {
  53. return validateBlock(blockExec.db, s, block)
  54. }
  55. // ApplyBlock validates the block against the state, executes it against the app,
  56. // fires the relevant events, commits the app, and saves the new state and responses.
  57. // It's the only function that needs to be called
  58. // from outside this package to process and commit an entire block.
  59. // It takes a blockID to avoid recomputing the parts hash.
  60. func (blockExec *BlockExecutor) ApplyBlock(s State, blockID types.BlockID, block *types.Block) (State, error) {
  61. if err := blockExec.ValidateBlock(s, block); err != nil {
  62. return s, ErrInvalidBlock(err)
  63. }
  64. abciResponses, err := execBlockOnProxyApp(blockExec.logger, blockExec.proxyApp, block)
  65. if err != nil {
  66. return s, ErrProxyAppConn(err)
  67. }
  68. fail.Fail() // XXX
  69. // save the results before we commit
  70. saveABCIResponses(blockExec.db, block.Height, abciResponses)
  71. fail.Fail() // XXX
  72. // update the state with the block and responses
  73. s, err = updateState(s, blockID, block.Header, abciResponses)
  74. if err != nil {
  75. return s, fmt.Errorf("Commit failed for application: %v", err)
  76. }
  77. // lock mempool, commit state, update mempoool
  78. appHash, err := blockExec.Commit(block)
  79. if err != nil {
  80. return s, fmt.Errorf("Commit failed for application: %v", err)
  81. }
  82. fail.Fail() // XXX
  83. // update the app hash and save the state
  84. s.AppHash = appHash
  85. SaveState(blockExec.db, s)
  86. fail.Fail() // XXX
  87. // Update evpool now that state is saved
  88. // TODO: handle the crash/recover scenario
  89. // ie. (may need to call Update for last block)
  90. blockExec.evpool.Update(block)
  91. // events are fired after everything else
  92. // NOTE: if we crash between Commit and Save, events wont be fired during replay
  93. fireEvents(blockExec.logger, blockExec.eventBus, block, abciResponses)
  94. return s, nil
  95. }
  96. // Commit locks the mempool, runs the ABCI Commit message, and updates the mempool.
  97. // It returns the result of calling abci.Commit (the AppHash), and an error.
  98. // The Mempool must be locked during commit and update because state is typically reset on Commit and old txs must be replayed
  99. // against committed state before new txs are run in the mempool, lest they be invalid.
  100. func (blockExec *BlockExecutor) Commit(block *types.Block) ([]byte, error) {
  101. blockExec.mempool.Lock()
  102. defer blockExec.mempool.Unlock()
  103. // Commit block, get hash back
  104. res, err := blockExec.proxyApp.CommitSync()
  105. if err != nil {
  106. blockExec.logger.Error("Client error during proxyAppConn.CommitSync", "err", err)
  107. return nil, err
  108. }
  109. if res.IsErr() {
  110. blockExec.logger.Error("Error in proxyAppConn.CommitSync", "err", res)
  111. return nil, res
  112. }
  113. if res.Log != "" {
  114. blockExec.logger.Debug("Commit.Log: " + res.Log)
  115. }
  116. blockExec.logger.Info("Committed state", "height", block.Height, "txs", block.NumTxs, "appHash", res.Data)
  117. // Update mempool.
  118. if err := blockExec.mempool.Update(block.Height, block.Txs); err != nil {
  119. return nil, err
  120. }
  121. return res.Data, nil
  122. }
  123. //---------------------------------------------------------
  124. // Helper functions for executing blocks and updating state
  125. // Executes block's transactions on proxyAppConn.
  126. // Returns a list of transaction results and updates to the validator set
  127. func execBlockOnProxyApp(logger log.Logger, proxyAppConn proxy.AppConnConsensus, block *types.Block) (*ABCIResponses, error) {
  128. var validTxs, invalidTxs = 0, 0
  129. txIndex := 0
  130. abciResponses := NewABCIResponses(block)
  131. // Execute transactions and get hash
  132. proxyCb := func(req *abci.Request, res *abci.Response) {
  133. switch r := res.Value.(type) {
  134. case *abci.Response_DeliverTx:
  135. // TODO: make use of res.Log
  136. // TODO: make use of this info
  137. // Blocks may include invalid txs.
  138. txRes := r.DeliverTx
  139. if txRes.Code == abci.CodeTypeOK {
  140. validTxs++
  141. } else {
  142. logger.Debug("Invalid tx", "code", txRes.Code, "log", txRes.Log)
  143. invalidTxs++
  144. }
  145. abciResponses.DeliverTx[txIndex] = txRes
  146. txIndex++
  147. }
  148. }
  149. proxyAppConn.SetResponseCallback(proxyCb)
  150. // determine which validators did not sign last block
  151. absentVals := make([]int32, 0)
  152. for valI, vote := range block.LastCommit.Precommits {
  153. if vote == nil {
  154. absentVals = append(absentVals, int32(valI))
  155. }
  156. }
  157. byzantineVals := make([]*abci.Evidence, len(block.Evidence.Evidence))
  158. for i, ev := range block.Evidence.Evidence {
  159. byzantineVals[i] = &abci.Evidence{
  160. PubKey: ev.Address(), // XXX/TODO
  161. Height: ev.Height(),
  162. }
  163. }
  164. // Begin block
  165. _, err := proxyAppConn.BeginBlockSync(abci.RequestBeginBlock{
  166. Hash: block.Hash(),
  167. Header: types.TM2PB.Header(block.Header),
  168. AbsentValidators: absentVals,
  169. ByzantineValidators: byzantineVals,
  170. })
  171. if err != nil {
  172. logger.Error("Error in proxyAppConn.BeginBlock", "err", err)
  173. return nil, err
  174. }
  175. // Run txs of block
  176. for _, tx := range block.Txs {
  177. proxyAppConn.DeliverTxAsync(tx)
  178. if err := proxyAppConn.Error(); err != nil {
  179. return nil, err
  180. }
  181. }
  182. // End block
  183. abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(abci.RequestEndBlock{block.Height})
  184. if err != nil {
  185. logger.Error("Error in proxyAppConn.EndBlock", "err", err)
  186. return nil, err
  187. }
  188. logger.Info("Executed block", "height", block.Height, "validTxs", validTxs, "invalidTxs", invalidTxs)
  189. valUpdates := abciResponses.EndBlock.ValidatorUpdates
  190. if len(valUpdates) > 0 {
  191. logger.Info("Updates to validators", "updates", abci.ValidatorsString(valUpdates))
  192. }
  193. return abciResponses, nil
  194. }
  195. func updateValidators(currentSet *types.ValidatorSet, updates []*abci.Validator) error {
  196. // If more or equal than 1/3 of total voting power changed in one block, then
  197. // a light client could never prove the transition externally. See
  198. // ./lite/doc.go for details on how a light client tracks validators.
  199. vp23, err := changeInVotingPowerMoreOrEqualToOneThird(currentSet, updates)
  200. if err != nil {
  201. return err
  202. }
  203. if vp23 {
  204. return errors.New("the change in voting power must be strictly less than 1/3")
  205. }
  206. for _, v := range updates {
  207. pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
  208. if err != nil {
  209. return err
  210. }
  211. address := pubkey.Address()
  212. power := int64(v.Power)
  213. // mind the overflow from int64
  214. if power < 0 {
  215. return fmt.Errorf("Power (%d) overflows int64", v.Power)
  216. }
  217. _, val := currentSet.GetByAddress(address)
  218. if val == nil {
  219. // add val
  220. added := currentSet.Add(types.NewValidator(pubkey, power))
  221. if !added {
  222. return fmt.Errorf("Failed to add new validator %X with voting power %d", address, power)
  223. }
  224. } else if v.Power == 0 {
  225. // remove val
  226. _, removed := currentSet.Remove(address)
  227. if !removed {
  228. return fmt.Errorf("Failed to remove validator %X", address)
  229. }
  230. } else {
  231. // update val
  232. val.VotingPower = power
  233. updated := currentSet.Update(val)
  234. if !updated {
  235. return fmt.Errorf("Failed to update validator %X with voting power %d", address, power)
  236. }
  237. }
  238. }
  239. return nil
  240. }
  241. func changeInVotingPowerMoreOrEqualToOneThird(currentSet *types.ValidatorSet, updates []*abci.Validator) (bool, error) {
  242. threshold := currentSet.TotalVotingPower() * 1 / 3
  243. acc := int64(0)
  244. for _, v := range updates {
  245. pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
  246. if err != nil {
  247. return false, err
  248. }
  249. address := pubkey.Address()
  250. power := int64(v.Power)
  251. // mind the overflow from int64
  252. if power < 0 {
  253. return false, fmt.Errorf("Power (%d) overflows int64", v.Power)
  254. }
  255. _, val := currentSet.GetByAddress(address)
  256. if val == nil {
  257. acc += power
  258. } else {
  259. np := val.VotingPower - power
  260. if np < 0 {
  261. np = -np
  262. }
  263. acc += np
  264. }
  265. if acc >= threshold {
  266. return true, nil
  267. }
  268. }
  269. return false, nil
  270. }
  271. // updateState returns a new State updated according to the header and responses.
  272. func updateState(s State, blockID types.BlockID, header *types.Header,
  273. abciResponses *ABCIResponses) (State, error) {
  274. // copy the valset so we can apply changes from EndBlock
  275. // and update s.LastValidators and s.Validators
  276. prevValSet := s.Validators.Copy()
  277. nextValSet := prevValSet.Copy()
  278. // update the validator set with the latest abciResponses
  279. lastHeightValsChanged := s.LastHeightValidatorsChanged
  280. if len(abciResponses.EndBlock.ValidatorUpdates) > 0 {
  281. err := updateValidators(nextValSet, abciResponses.EndBlock.ValidatorUpdates)
  282. if err != nil {
  283. return s, fmt.Errorf("Error changing validator set: %v", err)
  284. }
  285. // change results from this height but only applies to the next height
  286. lastHeightValsChanged = header.Height + 1
  287. }
  288. // Update validator accums and set state variables
  289. nextValSet.IncrementAccum(1)
  290. // update the params with the latest abciResponses
  291. nextParams := s.ConsensusParams
  292. lastHeightParamsChanged := s.LastHeightConsensusParamsChanged
  293. if abciResponses.EndBlock.ConsensusParamUpdates != nil {
  294. // NOTE: must not mutate s.ConsensusParams
  295. nextParams = s.ConsensusParams.Update(abciResponses.EndBlock.ConsensusParamUpdates)
  296. err := nextParams.Validate()
  297. if err != nil {
  298. return s, fmt.Errorf("Error updating consensus params: %v", err)
  299. }
  300. // change results from this height but only applies to the next height
  301. lastHeightParamsChanged = header.Height + 1
  302. }
  303. // NOTE: the AppHash has not been populated.
  304. // It will be filled on state.Save.
  305. return State{
  306. ChainID: s.ChainID,
  307. LastBlockHeight: header.Height,
  308. LastBlockTotalTx: s.LastBlockTotalTx + header.NumTxs,
  309. LastBlockID: blockID,
  310. LastBlockTime: header.Time,
  311. Validators: nextValSet,
  312. LastValidators: s.Validators.Copy(),
  313. LastHeightValidatorsChanged: lastHeightValsChanged,
  314. ConsensusParams: nextParams,
  315. LastHeightConsensusParamsChanged: lastHeightParamsChanged,
  316. LastResultsHash: abciResponses.ResultsHash(),
  317. AppHash: nil,
  318. }, nil
  319. }
  320. // Fire NewBlock, NewBlockHeader.
  321. // Fire TxEvent for every tx.
  322. // NOTE: if Tendermint crashes before commit, some or all of these events may be published again.
  323. func fireEvents(logger log.Logger, eventBus types.BlockEventPublisher, block *types.Block, abciResponses *ABCIResponses) {
  324. // NOTE: do we still need this buffer ?
  325. txEventBuffer := types.NewTxEventBuffer(eventBus, int(block.NumTxs))
  326. for i, tx := range block.Data.Txs {
  327. txEventBuffer.PublishEventTx(types.EventDataTx{types.TxResult{
  328. Height: block.Height,
  329. Index: uint32(i),
  330. Tx: tx,
  331. Result: *(abciResponses.DeliverTx[i]),
  332. }})
  333. }
  334. eventBus.PublishEventNewBlock(types.EventDataNewBlock{block})
  335. eventBus.PublishEventNewBlockHeader(types.EventDataNewBlockHeader{block.Header})
  336. err := txEventBuffer.Flush()
  337. if err != nil {
  338. logger.Error("Failed to flush event buffer", "err", err)
  339. }
  340. }
  341. //----------------------------------------------------------------------------------------------------
  342. // Execute block without state. TODO: eliminate
  343. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  344. // It returns the application root hash (result of abci.Commit).
  345. func ExecCommitBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block, logger log.Logger) ([]byte, error) {
  346. _, err := execBlockOnProxyApp(logger, appConnConsensus, block)
  347. if err != nil {
  348. logger.Error("Error executing block on proxy app", "height", block.Height, "err", err)
  349. return nil, err
  350. }
  351. // Commit block, get hash back
  352. res, err := appConnConsensus.CommitSync()
  353. if err != nil {
  354. logger.Error("Client error during proxyAppConn.CommitSync", "err", res)
  355. return nil, err
  356. }
  357. if res.IsErr() {
  358. logger.Error("Error in proxyAppConn.CommitSync", "err", res)
  359. return nil, res
  360. }
  361. if res.Log != "" {
  362. logger.Info("Commit.Log: " + res.Log)
  363. }
  364. return res.Data, nil
  365. }