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.

295 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.CodeType_OK {
  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. })
  72. if err != nil {
  73. logger.Error("Error in proxyAppConn.BeginBlock", "err", err)
  74. return nil, err
  75. }
  76. // Run txs of block
  77. for _, tx := range block.Txs {
  78. proxyAppConn.DeliverTxAsync(tx)
  79. if err := proxyAppConn.Error(); err != nil {
  80. return nil, err
  81. }
  82. }
  83. // End block
  84. abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(abci.RequestEndBlock{uint64(block.Height)})
  85. if err != nil {
  86. logger.Error("Error in proxyAppConn.EndBlock", "err", err)
  87. return nil, err
  88. }
  89. valDiff := abciResponses.EndBlock.Diffs
  90. logger.Info("Executed block", "height", block.Height, "validTxs", validTxs, "invalidTxs", invalidTxs)
  91. if len(valDiff) > 0 {
  92. logger.Info("Update to validator set", "updates", abci.ValidatorsString(valDiff))
  93. }
  94. return abciResponses, nil
  95. }
  96. func updateValidators(validators *types.ValidatorSet, changedValidators []*abci.Validator) error {
  97. // TODO: prevent change of 1/3+ at once
  98. for _, v := range changedValidators {
  99. pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
  100. if err != nil {
  101. return err
  102. }
  103. address := pubkey.Address()
  104. power := int64(v.Power)
  105. // mind the overflow from int64
  106. if power < 0 {
  107. return errors.New(cmn.Fmt("Power (%d) overflows int64", v.Power))
  108. }
  109. _, val := validators.GetByAddress(address)
  110. if val == nil {
  111. // add val
  112. added := validators.Add(types.NewValidator(pubkey, power))
  113. if !added {
  114. return errors.New(cmn.Fmt("Failed to add new validator %X with voting power %d", address, power))
  115. }
  116. } else if v.Power == 0 {
  117. // remove val
  118. _, removed := validators.Remove(address)
  119. if !removed {
  120. return errors.New(cmn.Fmt("Failed to remove validator %X)"))
  121. }
  122. } else {
  123. // update val
  124. val.VotingPower = power
  125. updated := validators.Update(val)
  126. if !updated {
  127. return errors.New(cmn.Fmt("Failed to update validator %X with voting power %d", address, power))
  128. }
  129. }
  130. }
  131. return nil
  132. }
  133. // return a bit array of validators that signed the last commit
  134. // NOTE: assumes commits have already been authenticated
  135. /* function is currently unused
  136. func commitBitArrayFromBlock(block *types.Block) *cmn.BitArray {
  137. signed := cmn.NewBitArray(len(block.LastCommit.Precommits))
  138. for i, precommit := range block.LastCommit.Precommits {
  139. if precommit != nil {
  140. signed.SetIndex(i, true) // val_.LastCommitHeight = block.Height - 1
  141. }
  142. }
  143. return signed
  144. }
  145. */
  146. //-----------------------------------------------------
  147. // Validate block
  148. // ValidateBlock validates the block against the state.
  149. func (s *State) ValidateBlock(block *types.Block) error {
  150. return s.validateBlock(block)
  151. }
  152. func (s *State) validateBlock(block *types.Block) error {
  153. // Basic block validation.
  154. err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockID, s.LastBlockTime, s.AppHash)
  155. if err != nil {
  156. return err
  157. }
  158. // Validate block LastCommit.
  159. if block.Height == 1 {
  160. if len(block.LastCommit.Precommits) != 0 {
  161. return errors.New("Block at height 1 (first block) should have no LastCommit precommits")
  162. }
  163. } else {
  164. if len(block.LastCommit.Precommits) != s.LastValidators.Size() {
  165. return errors.New(cmn.Fmt("Invalid block commit size. Expected %v, got %v",
  166. s.LastValidators.Size(), len(block.LastCommit.Precommits)))
  167. }
  168. err := s.LastValidators.VerifyCommit(
  169. s.ChainID, s.LastBlockID, block.Height-1, block.LastCommit)
  170. if err != nil {
  171. return err
  172. }
  173. }
  174. return nil
  175. }
  176. //-----------------------------------------------------------------------------
  177. // ApplyBlock validates & executes the block, updates state w/ ABCI responses,
  178. // then commits and updates the mempool atomically, then saves state.
  179. // ApplyBlock validates the block against the state, executes it against the app,
  180. // commits it, and saves the block and state. It's the only function that needs to be called
  181. // from outside this package to process and commit an entire block.
  182. func (s *State) ApplyBlock(txEventPublisher types.TxEventPublisher, proxyAppConn proxy.AppConnConsensus,
  183. block *types.Block, partsHeader types.PartSetHeader, mempool types.Mempool) error {
  184. abciResponses, err := s.ValExecBlock(txEventPublisher, proxyAppConn, block)
  185. if err != nil {
  186. return fmt.Errorf("Exec failed for application: %v", err)
  187. }
  188. fail.Fail() // XXX
  189. // save the results before we commit
  190. s.SaveABCIResponses(abciResponses)
  191. fail.Fail() // XXX
  192. // now update the block and validators
  193. s.SetBlockAndValidators(block.Header, partsHeader, abciResponses)
  194. // lock mempool, commit state, update mempoool
  195. err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
  196. if err != nil {
  197. return fmt.Errorf("Commit failed for application: %v", err)
  198. }
  199. fail.Fail() // XXX
  200. // save the state and the validators
  201. s.Save()
  202. return nil
  203. }
  204. // CommitStateUpdateMempool locks the mempool, runs the ABCI Commit message, and updates the mempool.
  205. // The Mempool must be locked during commit and update because state is typically reset on Commit and old txs must be replayed
  206. // against committed state before new txs are run in the mempool, lest they be invalid.
  207. func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, block *types.Block, mempool types.Mempool) error {
  208. mempool.Lock()
  209. defer mempool.Unlock()
  210. // Commit block, get hash back
  211. res, err := proxyAppConn.CommitSync()
  212. if err != nil {
  213. s.logger.Error("Client error during proxyAppConn.CommitSync", "err", err)
  214. return err
  215. }
  216. if res.IsErr() {
  217. s.logger.Error("Error in proxyAppConn.CommitSync", "err", res)
  218. return res
  219. }
  220. if res.Log != "" {
  221. s.logger.Debug("Commit.Log: " + res.Log)
  222. }
  223. s.logger.Info("Committed state", "height", block.Height, "txs", block.NumTxs, "hash", res.Data)
  224. // Set the state's new AppHash
  225. s.AppHash = res.Data
  226. // Update mempool.
  227. return mempool.Update(block.Height, block.Txs)
  228. }
  229. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  230. // It returns the application root hash (result of abci.Commit).
  231. func ExecCommitBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block, logger log.Logger) ([]byte, error) {
  232. _, err := execBlockOnProxyApp(types.NopEventBus{}, appConnConsensus, block, logger)
  233. if err != nil {
  234. logger.Error("Error executing block on proxy app", "height", block.Height, "err", err)
  235. return nil, err
  236. }
  237. // Commit block, get hash back
  238. res, err := appConnConsensus.CommitSync()
  239. if err != nil {
  240. logger.Error("Client error during proxyAppConn.CommitSync", "err", res)
  241. return nil, err
  242. }
  243. if res.IsErr() {
  244. logger.Error("Error in proxyAppConn.CommitSync", "err", res)
  245. return nil, res
  246. }
  247. if res.Log != "" {
  248. logger.Info("Commit.Log: " + res.Log)
  249. }
  250. return res.Data, nil
  251. }