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.

313 lines
9.5 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
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
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/state/txindex"
  10. "github.com/tendermint/tendermint/types"
  11. cmn "github.com/tendermint/tmlibs/common"
  12. "github.com/tendermint/tmlibs/log"
  13. )
  14. //--------------------------------------------------
  15. // Execute the block
  16. // ValExecBlock executes the block, but does NOT mutate State.
  17. // + validates the block
  18. // + executes block.Txs on the proxyAppConn
  19. func (s *State) ValExecBlock(txEventPublisher types.TxEventPublisher, proxyAppConn proxy.AppConnConsensus, block *types.Block) (*ABCIResponses, error) {
  20. // Validate the block.
  21. if err := s.validateBlock(block); err != nil {
  22. return nil, ErrInvalidBlock(err)
  23. }
  24. // Execute the block txs
  25. abciResponses, err := execBlockOnProxyApp(txEventPublisher, proxyAppConn, block, s.logger)
  26. if err != nil {
  27. // There was some error in proxyApp
  28. // TODO Report error and wait for proxyApp to be available.
  29. return nil, ErrProxyAppConn(err)
  30. }
  31. return abciResponses, nil
  32. }
  33. // Executes block's transactions on proxyAppConn.
  34. // Returns a list of transaction results and updates to the validator set
  35. // TODO: Generate a bitmap or otherwise store tx validity in state.
  36. func execBlockOnProxyApp(txEventPublisher types.TxEventPublisher, proxyAppConn proxy.AppConnConsensus, block *types.Block, logger log.Logger) (*ABCIResponses, error) {
  37. var validTxs, invalidTxs = 0, 0
  38. txIndex := 0
  39. abciResponses := NewABCIResponses(block)
  40. // Execute transactions and get hash
  41. proxyCb := func(req *abci.Request, res *abci.Response) {
  42. switch r := res.Value.(type) {
  43. case *abci.Response_DeliverTx:
  44. // TODO: make use of res.Log
  45. // TODO: make use of this info
  46. // Blocks may include invalid txs.
  47. // reqDeliverTx := req.(abci.RequestDeliverTx)
  48. txError := ""
  49. txResult := r.DeliverTx
  50. if txResult.Code == abci.CodeType_OK {
  51. validTxs++
  52. } else {
  53. logger.Debug("Invalid tx", "code", txResult.Code, "log", txResult.Log)
  54. invalidTxs++
  55. txError = txResult.Code.String()
  56. }
  57. abciResponses.DeliverTx[txIndex] = txResult
  58. txIndex++
  59. // NOTE: if we count we can access the tx from the block instead of
  60. // pulling it from the req
  61. event := types.EventDataTx{
  62. Height: block.Height,
  63. Tx: types.Tx(req.GetDeliverTx().Tx),
  64. Data: txResult.Data,
  65. Code: txResult.Code,
  66. Log: txResult.Log,
  67. Error: txError,
  68. }
  69. txEventPublisher.PublishEventTx(event)
  70. }
  71. }
  72. proxyAppConn.SetResponseCallback(proxyCb)
  73. // Begin block
  74. err := proxyAppConn.BeginBlockSync(abci.RequestBeginBlock{
  75. block.Hash(),
  76. types.TM2PB.Header(block.Header),
  77. })
  78. if err != nil {
  79. logger.Error("Error in proxyAppConn.BeginBlock", "err", err)
  80. return nil, err
  81. }
  82. // Run txs of block
  83. for _, tx := range block.Txs {
  84. proxyAppConn.DeliverTxAsync(tx)
  85. if err := proxyAppConn.Error(); err != nil {
  86. return nil, err
  87. }
  88. }
  89. // End block
  90. abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(uint64(block.Height))
  91. if err != nil {
  92. logger.Error("Error in proxyAppConn.EndBlock", "err", err)
  93. return nil, err
  94. }
  95. valDiff := abciResponses.EndBlock.Diffs
  96. logger.Info("Executed block", "height", block.Height, "validTxs", validTxs, "invalidTxs", invalidTxs)
  97. if len(valDiff) > 0 {
  98. logger.Info("Update to validator set", "updates", abci.ValidatorsString(valDiff))
  99. }
  100. return abciResponses, nil
  101. }
  102. func updateValidators(validators *types.ValidatorSet, changedValidators []*abci.Validator) error {
  103. // TODO: prevent change of 1/3+ at once
  104. for _, v := range changedValidators {
  105. pubkey, err := crypto.PubKeyFromBytes(v.PubKey) // NOTE: expects go-wire encoded pubkey
  106. if err != nil {
  107. return err
  108. }
  109. address := pubkey.Address()
  110. power := int64(v.Power)
  111. // mind the overflow from uint64
  112. if power < 0 {
  113. return errors.New(cmn.Fmt("Power (%d) overflows int64", v.Power))
  114. }
  115. _, val := validators.GetByAddress(address)
  116. if val == nil {
  117. // add val
  118. added := validators.Add(types.NewValidator(pubkey, power))
  119. if !added {
  120. return errors.New(cmn.Fmt("Failed to add new validator %X with voting power %d", address, power))
  121. }
  122. } else if v.Power == 0 {
  123. // remove val
  124. _, removed := validators.Remove(address)
  125. if !removed {
  126. return errors.New(cmn.Fmt("Failed to remove validator %X)"))
  127. }
  128. } else {
  129. // update val
  130. val.VotingPower = power
  131. updated := validators.Update(val)
  132. if !updated {
  133. return errors.New(cmn.Fmt("Failed to update validator %X with voting power %d", address, power))
  134. }
  135. }
  136. }
  137. return nil
  138. }
  139. // return a bit array of validators that signed the last commit
  140. // NOTE: assumes commits have already been authenticated
  141. func commitBitArrayFromBlock(block *types.Block) *cmn.BitArray {
  142. signed := cmn.NewBitArray(len(block.LastCommit.Precommits))
  143. for i, precommit := range block.LastCommit.Precommits {
  144. if precommit != nil {
  145. signed.SetIndex(i, true) // val_.LastCommitHeight = block.Height - 1
  146. }
  147. }
  148. return signed
  149. }
  150. //-----------------------------------------------------
  151. // Validate block
  152. // ValidateBlock validates the block against the state.
  153. func (s *State) ValidateBlock(block *types.Block) error {
  154. return s.validateBlock(block)
  155. }
  156. func (s *State) validateBlock(block *types.Block) error {
  157. // Basic block validation.
  158. err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockID, s.LastBlockTime, s.AppHash)
  159. if err != nil {
  160. return err
  161. }
  162. // Validate block LastCommit.
  163. if block.Height == 1 {
  164. if len(block.LastCommit.Precommits) != 0 {
  165. return errors.New("Block at height 1 (first block) should have no LastCommit precommits")
  166. }
  167. } else {
  168. if len(block.LastCommit.Precommits) != s.LastValidators.Size() {
  169. return errors.New(cmn.Fmt("Invalid block commit size. Expected %v, got %v",
  170. s.LastValidators.Size(), len(block.LastCommit.Precommits)))
  171. }
  172. err := s.LastValidators.VerifyCommit(
  173. s.ChainID, s.LastBlockID, block.Height-1, block.LastCommit)
  174. if err != nil {
  175. return err
  176. }
  177. }
  178. return nil
  179. }
  180. //-----------------------------------------------------------------------------
  181. // ApplyBlock validates & executes the block, updates state w/ ABCI responses,
  182. // then commits and updates the mempool atomically, then saves state.
  183. // Transaction results are optionally indexed.
  184. // ApplyBlock validates the block against the state, executes it against the app,
  185. // commits it, and saves the block and state. It's the only function that needs to be called
  186. // from outside this package to process and commit an entire block.
  187. func (s *State) ApplyBlock(txEventPublisher types.TxEventPublisher, proxyAppConn proxy.AppConnConsensus,
  188. block *types.Block, partsHeader types.PartSetHeader, mempool types.Mempool) error {
  189. abciResponses, err := s.ValExecBlock(txEventPublisher, proxyAppConn, block)
  190. if err != nil {
  191. return fmt.Errorf("Exec failed for application: %v", err)
  192. }
  193. fail.Fail() // XXX
  194. // index txs. This could run in the background
  195. s.indexTxs(abciResponses)
  196. // save the results before we commit
  197. s.SaveABCIResponses(abciResponses)
  198. fail.Fail() // XXX
  199. // now update the block and validators
  200. s.SetBlockAndValidators(block.Header, partsHeader, abciResponses)
  201. // lock mempool, commit state, update mempoool
  202. err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
  203. if err != nil {
  204. return fmt.Errorf("Commit failed for application: %v", err)
  205. }
  206. fail.Fail() // XXX
  207. // save the state and the validators
  208. s.Save()
  209. return nil
  210. }
  211. // CommitStateUpdateMempool locks the mempool, runs the ABCI Commit message, and updates the mempool.
  212. // The Mempool must be locked during commit and update because state is typically reset on Commit and old txs must be replayed
  213. // against committed state before new txs are run in the mempool, lest they be invalid.
  214. func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, block *types.Block, mempool types.Mempool) error {
  215. mempool.Lock()
  216. defer mempool.Unlock()
  217. // Commit block, get hash back
  218. res := proxyAppConn.CommitSync()
  219. if res.IsErr() {
  220. s.logger.Error("Error in proxyAppConn.CommitSync", "err", res)
  221. return res
  222. }
  223. if res.Log != "" {
  224. s.logger.Debug("Commit.Log: " + res.Log)
  225. }
  226. s.logger.Info("Committed state", "height", block.Height, "txs", block.NumTxs, "hash", res.Data)
  227. // Set the state's new AppHash
  228. s.AppHash = res.Data
  229. // Update mempool.
  230. mempool.Update(block.Height, block.Txs)
  231. return nil
  232. }
  233. func (s *State) indexTxs(abciResponses *ABCIResponses) {
  234. // save the tx results using the TxIndexer
  235. // NOTE: these may be overwriting, but the values should be the same.
  236. batch := txindex.NewBatch(len(abciResponses.DeliverTx))
  237. for i, d := range abciResponses.DeliverTx {
  238. tx := abciResponses.txs[i]
  239. batch.Add(types.TxResult{
  240. Height: uint64(abciResponses.Height),
  241. Index: uint32(i),
  242. Tx: tx,
  243. Result: *d,
  244. })
  245. }
  246. s.TxIndexer.AddBatch(batch)
  247. }
  248. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  249. // It returns the application root hash (result of abci.Commit).
  250. func ExecCommitBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block, logger log.Logger) ([]byte, error) {
  251. _, err := execBlockOnProxyApp(types.NopEventBus{}, appConnConsensus, block, logger)
  252. if err != nil {
  253. logger.Error("Error executing block on proxy app", "height", block.Height, "err", err)
  254. return nil, err
  255. }
  256. // Commit block, get hash back
  257. res := appConnConsensus.CommitSync()
  258. if res.IsErr() {
  259. logger.Error("Error in proxyAppConn.CommitSync", "err", res)
  260. return nil, res
  261. }
  262. if res.Log != "" {
  263. logger.Info("Commit.Log: " + res.Log)
  264. }
  265. return res.Data, nil
  266. }