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.

297 lines
9.1 KiB

8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
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
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
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. cmn "github.com/tendermint/tmlibs/common"
  11. "github.com/tendermint/tmlibs/log"
  12. )
  13. //--------------------------------------------------
  14. // Execute the block
  15. // ValExecBlock executes the block, but does NOT mutate State.
  16. // + validates the block
  17. // + executes block.Txs on the proxyAppConn
  18. func (s *State) ValExecBlock(txEventPublisher types.TxEventPublisher, proxyAppConn proxy.AppConnConsensus, block *types.Block) (*ABCIResponses, error) {
  19. // Validate the block.
  20. if err := s.validateBlock(block); err != nil {
  21. return nil, ErrInvalidBlock(err)
  22. }
  23. // Execute the block txs
  24. abciResponses, err := execBlockOnProxyApp(txEventPublisher, proxyAppConn, block, s.logger)
  25. if err != nil {
  26. // There was some error in proxyApp
  27. // TODO Report error and wait for proxyApp to be available.
  28. return nil, ErrProxyAppConn(err)
  29. }
  30. return abciResponses, nil
  31. }
  32. // Executes block's transactions on proxyAppConn.
  33. // Returns a list of transaction results and updates to the validator set
  34. // TODO: Generate a bitmap or otherwise store tx validity in state.
  35. func execBlockOnProxyApp(txEventPublisher types.TxEventPublisher, proxyAppConn proxy.AppConnConsensus, block *types.Block, logger log.Logger) (*ABCIResponses, error) {
  36. var validTxs, invalidTxs = 0, 0
  37. txIndex := 0
  38. abciResponses := NewABCIResponses(block)
  39. // Execute transactions and get hash
  40. proxyCb := func(req *abci.Request, res *abci.Response) {
  41. switch r := res.Value.(type) {
  42. case *abci.Response_DeliverTx:
  43. // TODO: make use of res.Log
  44. // TODO: make use of this info
  45. // Blocks may include invalid txs.
  46. // reqDeliverTx := req.(abci.RequestDeliverTx)
  47. txResult := r.DeliverTx
  48. if txResult.Code == abci.CodeTypeOK {
  49. validTxs++
  50. } else {
  51. logger.Debug("Invalid tx", "code", txResult.Code, "log", txResult.Log)
  52. invalidTxs++
  53. }
  54. // NOTE: if we count we can access the tx from the block instead of
  55. // pulling it from the req
  56. txEventPublisher.PublishEventTx(types.EventDataTx{types.TxResult{
  57. Height: block.Height,
  58. Index: uint32(txIndex),
  59. Tx: types.Tx(req.GetDeliverTx().Tx),
  60. Result: *txResult,
  61. }})
  62. abciResponses.DeliverTx[txIndex] = txResult
  63. txIndex++
  64. }
  65. }
  66. proxyAppConn.SetResponseCallback(proxyCb)
  67. // Begin block
  68. _, err := proxyAppConn.BeginBlockSync(abci.RequestBeginBlock{
  69. block.Hash(),
  70. types.TM2PB.Header(block.Header),
  71. nil,
  72. nil,
  73. })
  74. if err != nil {
  75. logger.Error("Error in proxyAppConn.BeginBlock", "err", err)
  76. return nil, err
  77. }
  78. // Run txs of block
  79. for _, tx := range block.Txs {
  80. proxyAppConn.DeliverTxAsync(tx)
  81. if err := proxyAppConn.Error(); err != nil {
  82. return nil, err
  83. }
  84. }
  85. // End block
  86. abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(abci.RequestEndBlock{block.Height})
  87. if err != nil {
  88. logger.Error("Error in proxyAppConn.EndBlock", "err", err)
  89. return nil, err
  90. }
  91. valDiff := abciResponses.EndBlock.Diffs
  92. logger.Info("Executed block", "height", block.Height, "validTxs", validTxs, "invalidTxs", invalidTxs)
  93. if len(valDiff) > 0 {
  94. logger.Info("Update to validator set", "updates", abci.ValidatorsString(valDiff))
  95. }
  96. return abciResponses, nil
  97. }
  98. func updateValidators(validators *types.ValidatorSet, changedValidators []*abci.Validator) error {
  99. // TODO: prevent change of 1/3+ at once
  100. for _, v := range changedValidators {
  101. pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
  102. if err != nil {
  103. return err
  104. }
  105. address := pubkey.Address()
  106. power := int64(v.Power)
  107. // mind the overflow from int64
  108. if power < 0 {
  109. return errors.New(cmn.Fmt("Power (%d) overflows int64", v.Power))
  110. }
  111. _, val := validators.GetByAddress(address)
  112. if val == nil {
  113. // add val
  114. added := validators.Add(types.NewValidator(pubkey, power))
  115. if !added {
  116. return errors.New(cmn.Fmt("Failed to add new validator %X with voting power %d", address, power))
  117. }
  118. } else if v.Power == 0 {
  119. // remove val
  120. _, removed := validators.Remove(address)
  121. if !removed {
  122. return errors.New(cmn.Fmt("Failed to remove validator %X)"))
  123. }
  124. } else {
  125. // update val
  126. val.VotingPower = power
  127. updated := validators.Update(val)
  128. if !updated {
  129. return errors.New(cmn.Fmt("Failed to update validator %X with voting power %d", address, power))
  130. }
  131. }
  132. }
  133. return nil
  134. }
  135. // return a bit array of validators that signed the last commit
  136. // NOTE: assumes commits have already been authenticated
  137. /* function is currently unused
  138. func commitBitArrayFromBlock(block *types.Block) *cmn.BitArray {
  139. signed := cmn.NewBitArray(len(block.LastCommit.Precommits))
  140. for i, precommit := range block.LastCommit.Precommits {
  141. if precommit != nil {
  142. signed.SetIndex(i, true) // val_.LastCommitHeight = block.Height - 1
  143. }
  144. }
  145. return signed
  146. }
  147. */
  148. //-----------------------------------------------------
  149. // Validate block
  150. // ValidateBlock validates the block against the state.
  151. func (s *State) ValidateBlock(block *types.Block) error {
  152. return s.validateBlock(block)
  153. }
  154. func (s *State) validateBlock(block *types.Block) error {
  155. // Basic block validation.
  156. err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockID, s.LastBlockTime, s.AppHash)
  157. if err != nil {
  158. return err
  159. }
  160. // Validate block LastCommit.
  161. if block.Height == 1 {
  162. if len(block.LastCommit.Precommits) != 0 {
  163. return errors.New("Block at height 1 (first block) should have no LastCommit precommits")
  164. }
  165. } else {
  166. if len(block.LastCommit.Precommits) != s.LastValidators.Size() {
  167. return errors.New(cmn.Fmt("Invalid block commit size. Expected %v, got %v",
  168. s.LastValidators.Size(), len(block.LastCommit.Precommits)))
  169. }
  170. err := s.LastValidators.VerifyCommit(
  171. s.ChainID, s.LastBlockID, block.Height-1, block.LastCommit)
  172. if err != nil {
  173. return err
  174. }
  175. }
  176. return nil
  177. }
  178. //-----------------------------------------------------------------------------
  179. // ApplyBlock validates & executes the block, updates state w/ ABCI responses,
  180. // then commits and updates the mempool atomically, then saves state.
  181. // ApplyBlock validates the block against the state, executes it against the app,
  182. // commits it, and saves the block and state. It's the only function that needs to be called
  183. // from outside this package to process and commit an entire block.
  184. func (s *State) ApplyBlock(txEventPublisher types.TxEventPublisher, proxyAppConn proxy.AppConnConsensus,
  185. block *types.Block, partsHeader types.PartSetHeader, mempool types.Mempool) error {
  186. abciResponses, err := s.ValExecBlock(txEventPublisher, proxyAppConn, block)
  187. if err != nil {
  188. return fmt.Errorf("Exec failed for application: %v", err)
  189. }
  190. fail.Fail() // XXX
  191. // save the results before we commit
  192. s.SaveABCIResponses(abciResponses)
  193. fail.Fail() // XXX
  194. // now update the block and validators
  195. s.SetBlockAndValidators(block.Header, partsHeader, abciResponses)
  196. // lock mempool, commit state, update mempoool
  197. err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
  198. if err != nil {
  199. return fmt.Errorf("Commit failed for application: %v", err)
  200. }
  201. fail.Fail() // XXX
  202. // save the state and the validators
  203. s.Save()
  204. return nil
  205. }
  206. // CommitStateUpdateMempool locks the mempool, runs the ABCI Commit message, and updates the mempool.
  207. // The Mempool must be locked during commit and update because state is typically reset on Commit and old txs must be replayed
  208. // against committed state before new txs are run in the mempool, lest they be invalid.
  209. func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, block *types.Block, mempool types.Mempool) error {
  210. mempool.Lock()
  211. defer mempool.Unlock()
  212. // Commit block, get hash back
  213. res, err := proxyAppConn.CommitSync()
  214. if err != nil {
  215. s.logger.Error("Client error during proxyAppConn.CommitSync", "err", err)
  216. return err
  217. }
  218. if res.IsErr() {
  219. s.logger.Error("Error in proxyAppConn.CommitSync", "err", res)
  220. return res
  221. }
  222. if res.Log != "" {
  223. s.logger.Debug("Commit.Log: " + res.Log)
  224. }
  225. s.logger.Info("Committed state", "height", block.Height, "txs", block.NumTxs, "hash", res.Data)
  226. // Set the state's new AppHash
  227. s.AppHash = res.Data
  228. // Update mempool.
  229. return mempool.Update(block.Height, block.Txs)
  230. }
  231. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  232. // It returns the application root hash (result of abci.Commit).
  233. func ExecCommitBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block, logger log.Logger) ([]byte, error) {
  234. _, err := execBlockOnProxyApp(types.NopEventBus{}, appConnConsensus, block, logger)
  235. if err != nil {
  236. logger.Error("Error executing block on proxy app", "height", block.Height, "err", err)
  237. return nil, err
  238. }
  239. // Commit block, get hash back
  240. res, err := appConnConsensus.CommitSync()
  241. if err != nil {
  242. logger.Error("Client error during proxyAppConn.CommitSync", "err", res)
  243. return nil, err
  244. }
  245. if res.IsErr() {
  246. logger.Error("Error in proxyAppConn.CommitSync", "err", res)
  247. return nil, res
  248. }
  249. if res.Log != "" {
  250. logger.Info("Commit.Log: " + res.Log)
  251. }
  252. return res.Data, nil
  253. }