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.

317 lines
9.7 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. /* function is currently unused
  142. func commitBitArrayFromBlock(block *types.Block) *cmn.BitArray {
  143. signed := cmn.NewBitArray(len(block.LastCommit.Precommits))
  144. for i, precommit := range block.LastCommit.Precommits {
  145. if precommit != nil {
  146. signed.SetIndex(i, true) // val_.LastCommitHeight = block.Height - 1
  147. }
  148. }
  149. return signed
  150. }
  151. */
  152. //-----------------------------------------------------
  153. // Validate block
  154. // ValidateBlock validates the block against the state.
  155. func (s *State) ValidateBlock(block *types.Block) error {
  156. return s.validateBlock(block)
  157. }
  158. func (s *State) validateBlock(block *types.Block) error {
  159. // Basic block validation.
  160. err := block.ValidateBasic(s.ChainID, s.LastBlockHeight, s.LastBlockID, s.LastBlockTime, s.AppHash)
  161. if err != nil {
  162. return err
  163. }
  164. // Validate block LastCommit.
  165. if block.Height == 1 {
  166. if len(block.LastCommit.Precommits) != 0 {
  167. return errors.New("Block at height 1 (first block) should have no LastCommit precommits")
  168. }
  169. } else {
  170. if len(block.LastCommit.Precommits) != s.LastValidators.Size() {
  171. return errors.New(cmn.Fmt("Invalid block commit size. Expected %v, got %v",
  172. s.LastValidators.Size(), len(block.LastCommit.Precommits)))
  173. }
  174. err := s.LastValidators.VerifyCommit(
  175. s.ChainID, s.LastBlockID, block.Height-1, block.LastCommit)
  176. if err != nil {
  177. return err
  178. }
  179. }
  180. return nil
  181. }
  182. //-----------------------------------------------------------------------------
  183. // ApplyBlock validates & executes the block, updates state w/ ABCI responses,
  184. // then commits and updates the mempool atomically, then saves state.
  185. // Transaction results are optionally indexed.
  186. // ApplyBlock validates the block against the state, executes it against the app,
  187. // commits it, and saves the block and state. It's the only function that needs to be called
  188. // from outside this package to process and commit an entire block.
  189. func (s *State) ApplyBlock(txEventPublisher types.TxEventPublisher, proxyAppConn proxy.AppConnConsensus,
  190. block *types.Block, partsHeader types.PartSetHeader, mempool types.Mempool) error {
  191. abciResponses, err := s.ValExecBlock(txEventPublisher, proxyAppConn, block)
  192. if err != nil {
  193. return fmt.Errorf("Exec failed for application: %v", err)
  194. }
  195. fail.Fail() // XXX
  196. // index txs. This could run in the background
  197. s.indexTxs(abciResponses)
  198. // save the results before we commit
  199. s.SaveABCIResponses(abciResponses)
  200. fail.Fail() // XXX
  201. // now update the block and validators
  202. s.SetBlockAndValidators(block.Header, partsHeader, abciResponses)
  203. // lock mempool, commit state, update mempoool
  204. err = s.CommitStateUpdateMempool(proxyAppConn, block, mempool)
  205. if err != nil {
  206. return fmt.Errorf("Commit failed for application: %v", err)
  207. }
  208. fail.Fail() // XXX
  209. // save the state and the validators
  210. s.Save()
  211. return nil
  212. }
  213. // CommitStateUpdateMempool locks the mempool, runs the ABCI Commit message, and updates the mempool.
  214. // The Mempool must be locked during commit and update because state is typically reset on Commit and old txs must be replayed
  215. // against committed state before new txs are run in the mempool, lest they be invalid.
  216. func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, block *types.Block, mempool types.Mempool) error {
  217. mempool.Lock()
  218. defer mempool.Unlock()
  219. // Commit block, get hash back
  220. res := proxyAppConn.CommitSync()
  221. if res.IsErr() {
  222. s.logger.Error("Error in proxyAppConn.CommitSync", "err", res)
  223. return res
  224. }
  225. if res.Log != "" {
  226. s.logger.Debug("Commit.Log: " + res.Log)
  227. }
  228. s.logger.Info("Committed state", "height", block.Height, "txs", block.NumTxs, "hash", res.Data)
  229. // Set the state's new AppHash
  230. s.AppHash = res.Data
  231. // Update mempool.
  232. return mempool.Update(block.Height, block.Txs)
  233. }
  234. func (s *State) indexTxs(abciResponses *ABCIResponses) {
  235. // save the tx results using the TxIndexer
  236. // NOTE: these may be overwriting, but the values should be the same.
  237. batch := txindex.NewBatch(len(abciResponses.DeliverTx))
  238. for i, d := range abciResponses.DeliverTx {
  239. tx := abciResponses.txs[i]
  240. if err := batch.Add(types.TxResult{
  241. Height: uint64(abciResponses.Height),
  242. Index: uint32(i),
  243. Tx: tx,
  244. Result: *d,
  245. }); err != nil {
  246. s.logger.Error("Error with batch.Add", "err", err)
  247. }
  248. }
  249. if err := s.TxIndexer.AddBatch(batch); err != nil {
  250. s.logger.Error("Error adding batch", "err", err)
  251. }
  252. }
  253. // ExecCommitBlock executes and commits a block on the proxyApp without validating or mutating the state.
  254. // It returns the application root hash (result of abci.Commit).
  255. func ExecCommitBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block, logger log.Logger) ([]byte, error) {
  256. _, err := execBlockOnProxyApp(types.NopEventBus{}, appConnConsensus, block, logger)
  257. if err != nil {
  258. logger.Error("Error executing block on proxy app", "height", block.Height, "err", err)
  259. return nil, err
  260. }
  261. // Commit block, get hash back
  262. res := appConnConsensus.CommitSync()
  263. if res.IsErr() {
  264. logger.Error("Error in proxyAppConn.CommitSync", "err", res)
  265. return nil, res
  266. }
  267. if res.Log != "" {
  268. logger.Info("Commit.Log: " + res.Log)
  269. }
  270. return res.Data, nil
  271. }