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.

428 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. // TODO: determine which validators were byzantine
  158. byzantineVals := make([]*abci.Evidence, len(block.Evidence.Evidence))
  159. for i, ev := range block.Evidence.Evidence {
  160. byzantineVals[i] = &abci.Evidence{
  161. PubKey: ev.Address(), // XXX
  162. Height: ev.Height(),
  163. }
  164. }
  165. // Begin block
  166. _, err := proxyAppConn.BeginBlockSync(abci.RequestBeginBlock{
  167. Hash: block.Hash(),
  168. Header: types.TM2PB.Header(block.Header),
  169. AbsentValidators: absentVals,
  170. ByzantineValidators: byzantineVals,
  171. })
  172. if err != nil {
  173. logger.Error("Error in proxyAppConn.BeginBlock", "err", err)
  174. return nil, err
  175. }
  176. // Run txs of block
  177. for _, tx := range block.Txs {
  178. proxyAppConn.DeliverTxAsync(tx)
  179. if err := proxyAppConn.Error(); err != nil {
  180. return nil, err
  181. }
  182. }
  183. // End block
  184. abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(abci.RequestEndBlock{block.Height})
  185. if err != nil {
  186. logger.Error("Error in proxyAppConn.EndBlock", "err", err)
  187. return nil, err
  188. }
  189. logger.Info("Executed block", "height", block.Height, "validTxs", validTxs, "invalidTxs", invalidTxs)
  190. valUpdates := abciResponses.EndBlock.ValidatorUpdates
  191. if len(valUpdates) > 0 {
  192. logger.Info("Updates to validators", "updates", abci.ValidatorsString(valUpdates))
  193. }
  194. return abciResponses, nil
  195. }
  196. func updateValidators(currentSet *types.ValidatorSet, updates []*abci.Validator) error {
  197. // If more or equal than 1/3 of total voting power changed in one block, then
  198. // a light client could never prove the transition externally. See
  199. // ./lite/doc.go for details on how a light client tracks validators.
  200. vp23, err := changeInVotingPowerMoreOrEqualToOneThird(currentSet, updates)
  201. if err != nil {
  202. return err
  203. }
  204. if vp23 {
  205. return errors.New("the change in voting power must be strictly less than 1/3")
  206. }
  207. for _, v := range updates {
  208. pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
  209. if err != nil {
  210. return err
  211. }
  212. address := pubkey.Address()
  213. power := int64(v.Power)
  214. // mind the overflow from int64
  215. if power < 0 {
  216. return fmt.Errorf("Power (%d) overflows int64", v.Power)
  217. }
  218. _, val := currentSet.GetByAddress(address)
  219. if val == nil {
  220. // add val
  221. added := currentSet.Add(types.NewValidator(pubkey, power))
  222. if !added {
  223. return fmt.Errorf("Failed to add new validator %X with voting power %d", address, power)
  224. }
  225. } else if v.Power == 0 {
  226. // remove val
  227. _, removed := currentSet.Remove(address)
  228. if !removed {
  229. return fmt.Errorf("Failed to remove validator %X", address)
  230. }
  231. } else {
  232. // update val
  233. val.VotingPower = power
  234. updated := currentSet.Update(val)
  235. if !updated {
  236. return fmt.Errorf("Failed to update validator %X with voting power %d", address, power)
  237. }
  238. }
  239. }
  240. return nil
  241. }
  242. func changeInVotingPowerMoreOrEqualToOneThird(currentSet *types.ValidatorSet, updates []*abci.Validator) (bool, error) {
  243. threshold := currentSet.TotalVotingPower() * 1 / 3
  244. acc := int64(0)
  245. for _, v := range updates {
  246. pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
  247. if err != nil {
  248. return false, err
  249. }
  250. address := pubkey.Address()
  251. power := int64(v.Power)
  252. // mind the overflow from int64
  253. if power < 0 {
  254. return false, fmt.Errorf("Power (%d) overflows int64", v.Power)
  255. }
  256. _, val := currentSet.GetByAddress(address)
  257. if val == nil {
  258. acc += power
  259. } else {
  260. np := val.VotingPower - power
  261. if np < 0 {
  262. np = -np
  263. }
  264. acc += np
  265. }
  266. if acc >= threshold {
  267. return true, nil
  268. }
  269. }
  270. return false, nil
  271. }
  272. // updateState returns a new State updated according to the header and responses.
  273. func updateState(s State, blockID types.BlockID, header *types.Header,
  274. abciResponses *ABCIResponses) (State, error) {
  275. // copy the valset so we can apply changes from EndBlock
  276. // and update s.LastValidators and s.Validators
  277. prevValSet := s.Validators.Copy()
  278. nextValSet := prevValSet.Copy()
  279. // update the validator set with the latest abciResponses
  280. lastHeightValsChanged := s.LastHeightValidatorsChanged
  281. if len(abciResponses.EndBlock.ValidatorUpdates) > 0 {
  282. err := updateValidators(nextValSet, abciResponses.EndBlock.ValidatorUpdates)
  283. if err != nil {
  284. return s, fmt.Errorf("Error changing validator set: %v", err)
  285. }
  286. // change results from this height but only applies to the next height
  287. lastHeightValsChanged = header.Height + 1
  288. }
  289. // Update validator accums and set state variables
  290. nextValSet.IncrementAccum(1)
  291. // update the params with the latest abciResponses
  292. nextParams := s.ConsensusParams
  293. lastHeightParamsChanged := s.LastHeightConsensusParamsChanged
  294. if abciResponses.EndBlock.ConsensusParamUpdates != nil {
  295. // NOTE: must not mutate s.ConsensusParams
  296. nextParams = s.ConsensusParams.Update(abciResponses.EndBlock.ConsensusParamUpdates)
  297. err := nextParams.Validate()
  298. if err != nil {
  299. return s, fmt.Errorf("Error updating consensus params: %v", err)
  300. }
  301. // change results from this height but only applies to the next height
  302. lastHeightParamsChanged = header.Height + 1
  303. }
  304. // NOTE: the AppHash has not been populated.
  305. // It will be filled on state.Save.
  306. return State{
  307. ChainID: s.ChainID,
  308. LastBlockHeight: header.Height,
  309. LastBlockTotalTx: s.LastBlockTotalTx + header.NumTxs,
  310. LastBlockID: blockID,
  311. LastBlockTime: header.Time,
  312. Validators: nextValSet,
  313. LastValidators: s.Validators.Copy(),
  314. LastHeightValidatorsChanged: lastHeightValsChanged,
  315. ConsensusParams: nextParams,
  316. LastHeightConsensusParamsChanged: lastHeightParamsChanged,
  317. LastResultsHash: abciResponses.ResultsHash(),
  318. AppHash: nil,
  319. }, nil
  320. }
  321. // Fire NewBlock, NewBlockHeader.
  322. // Fire TxEvent for every tx.
  323. // NOTE: if Tendermint crashes before commit, some or all of these events may be published again.
  324. func fireEvents(logger log.Logger, eventBus types.BlockEventPublisher, block *types.Block, abciResponses *ABCIResponses) {
  325. // NOTE: do we still need this buffer ?
  326. txEventBuffer := types.NewTxEventBuffer(eventBus, int(block.NumTxs))
  327. for i, tx := range block.Data.Txs {
  328. txEventBuffer.PublishEventTx(types.EventDataTx{types.TxResult{
  329. Height: block.Height,
  330. Index: uint32(i),
  331. Tx: tx,
  332. Result: *(abciResponses.DeliverTx[i]),
  333. }})
  334. }
  335. eventBus.PublishEventNewBlock(types.EventDataNewBlock{block})
  336. eventBus.PublishEventNewBlockHeader(types.EventDataNewBlockHeader{block.Header})
  337. err := txEventBuffer.Flush()
  338. if err != nil {
  339. logger.Error("Failed to flush event buffer", "err", err)
  340. }
  341. }
  342. //----------------------------------------------------------------------------------------------------
  343. // Execute block without state. TODO: eliminate
  344. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  345. // It returns the application root hash (result of abci.Commit).
  346. func ExecCommitBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block, logger log.Logger) ([]byte, error) {
  347. _, err := execBlockOnProxyApp(logger, appConnConsensus, block)
  348. if err != nil {
  349. logger.Error("Error executing block on proxy app", "height", block.Height, "err", err)
  350. return nil, err
  351. }
  352. // Commit block, get hash back
  353. res, err := appConnConsensus.CommitSync()
  354. if err != nil {
  355. logger.Error("Client error during proxyAppConn.CommitSync", "err", res)
  356. return nil, err
  357. }
  358. if res.IsErr() {
  359. logger.Error("Error in proxyAppConn.CommitSync", "err", res)
  360. return nil, res
  361. }
  362. if res.Log != "" {
  363. logger.Info("Commit.Log: " + res.Log)
  364. }
  365. return res.Data, nil
  366. }