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.

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