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.

1697 lines
59 KiB

10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 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
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
10 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
10 years ago
9 years ago
10 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
fix data race Closes #1442 ``` WARNING: DATA RACE Write at 0x00c4209de7c8 by goroutine 23: github.com/tendermint/tendermint/types.(*Block).fillHeader() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:88 +0x157 github.com/tendermint/tendermint/types.(*Block).Hash() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:104 +0x121 github.com/tendermint/tendermint/types.(*Block).HashesTo() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:135 +0x4f github.com/tendermint/tendermint/consensus.(*ConsensusState).enterPrecommit() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1037 +0x182d github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1425 +0x1a6c github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1318 +0x77 github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:581 +0x7a9 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:539 +0x6c3 Previous read at 0x00c4209de7c8 by goroutine 47: github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*HexBytes).MarshalJSON() <autogenerated>:1 +0x52 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.invokeMarshalJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:433 +0x88 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:82 +0x8d2 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).MarshalJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/amino.go:296 +0x182 github.com/tendermint/tendermint/rpc/lib/types.NewRPCSuccessResponse() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/types/types.go:100 +0x12c github.com/tendermint/tendermint/rpc/lib/server.makeJSONRPCHandler.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/handlers.go:152 +0xab7 net/http.HandlerFunc.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:1918 +0x51 net/http.(*ServeMux).ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:2254 +0xa2 github.com/tendermint/tendermint/rpc/lib/server.RecoverAndLogHandler.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:138 +0x4fa net/http.HandlerFunc.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:1918 +0x51 net/http.serverHandler.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:2619 +0xbc net/http.(*conn).serve() /usr/lib/go-1.9/src/net/http/server.go:1801 +0x83b Goroutine 23 (running) created at: github.com/tendermint/tendermint/consensus.(*ConsensusState).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:250 +0x35b github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/consensus.(*ConsensusReactor).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/reactor.go:69 +0x1b4 github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/consensus.(*ConsensusReactor).Start() <autogenerated>:1 +0x43 github.com/tendermint/tendermint/p2p.(*Switch).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch.go:177 +0x124 github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/node.(*Node).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/node/node.go:416 +0xa1b github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/rpc/test.StartTendermint() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/test/helpers.go:100 +0x5b github.com/tendermint/tendermint/rpc/client_test.TestMain() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/client/main_test.go:17 +0x4c main.main() github.com/tendermint/tendermint/rpc/client/_test/_testmain.go:76 +0x1cd Goroutine 47 (running) created at: net/http.(*Server).Serve() /usr/lib/go-1.9/src/net/http/server.go:2720 +0x37c net/http.Serve() /usr/lib/go-1.9/src/net/http/server.go:2323 +0xe2 github.com/tendermint/tendermint/rpc/lib/server.StartHTTPServer.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:35 +0xb3 ```
7 years ago
10 years ago
10 years ago
fix data race Closes #1442 ``` WARNING: DATA RACE Write at 0x00c4209de7c8 by goroutine 23: github.com/tendermint/tendermint/types.(*Block).fillHeader() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:88 +0x157 github.com/tendermint/tendermint/types.(*Block).Hash() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:104 +0x121 github.com/tendermint/tendermint/types.(*Block).HashesTo() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:135 +0x4f github.com/tendermint/tendermint/consensus.(*ConsensusState).enterPrecommit() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1037 +0x182d github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1425 +0x1a6c github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1318 +0x77 github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:581 +0x7a9 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:539 +0x6c3 Previous read at 0x00c4209de7c8 by goroutine 47: github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*HexBytes).MarshalJSON() <autogenerated>:1 +0x52 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.invokeMarshalJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:433 +0x88 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:82 +0x8d2 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).MarshalJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/amino.go:296 +0x182 github.com/tendermint/tendermint/rpc/lib/types.NewRPCSuccessResponse() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/types/types.go:100 +0x12c github.com/tendermint/tendermint/rpc/lib/server.makeJSONRPCHandler.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/handlers.go:152 +0xab7 net/http.HandlerFunc.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:1918 +0x51 net/http.(*ServeMux).ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:2254 +0xa2 github.com/tendermint/tendermint/rpc/lib/server.RecoverAndLogHandler.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:138 +0x4fa net/http.HandlerFunc.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:1918 +0x51 net/http.serverHandler.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:2619 +0xbc net/http.(*conn).serve() /usr/lib/go-1.9/src/net/http/server.go:1801 +0x83b Goroutine 23 (running) created at: github.com/tendermint/tendermint/consensus.(*ConsensusState).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:250 +0x35b github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/consensus.(*ConsensusReactor).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/reactor.go:69 +0x1b4 github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/consensus.(*ConsensusReactor).Start() <autogenerated>:1 +0x43 github.com/tendermint/tendermint/p2p.(*Switch).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch.go:177 +0x124 github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/node.(*Node).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/node/node.go:416 +0xa1b github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/rpc/test.StartTendermint() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/test/helpers.go:100 +0x5b github.com/tendermint/tendermint/rpc/client_test.TestMain() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/client/main_test.go:17 +0x4c main.main() github.com/tendermint/tendermint/rpc/client/_test/_testmain.go:76 +0x1cd Goroutine 47 (running) created at: net/http.(*Server).Serve() /usr/lib/go-1.9/src/net/http/server.go:2720 +0x37c net/http.Serve() /usr/lib/go-1.9/src/net/http/server.go:2323 +0xe2 github.com/tendermint/tendermint/rpc/lib/server.StartHTTPServer.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:35 +0xb3 ```
7 years ago
fix data race Closes #1442 ``` WARNING: DATA RACE Write at 0x00c4209de7c8 by goroutine 23: github.com/tendermint/tendermint/types.(*Block).fillHeader() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:88 +0x157 github.com/tendermint/tendermint/types.(*Block).Hash() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:104 +0x121 github.com/tendermint/tendermint/types.(*Block).HashesTo() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:135 +0x4f github.com/tendermint/tendermint/consensus.(*ConsensusState).enterPrecommit() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1037 +0x182d github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1425 +0x1a6c github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1318 +0x77 github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:581 +0x7a9 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:539 +0x6c3 Previous read at 0x00c4209de7c8 by goroutine 47: github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*HexBytes).MarshalJSON() <autogenerated>:1 +0x52 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.invokeMarshalJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:433 +0x88 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:82 +0x8d2 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).MarshalJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/amino.go:296 +0x182 github.com/tendermint/tendermint/rpc/lib/types.NewRPCSuccessResponse() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/types/types.go:100 +0x12c github.com/tendermint/tendermint/rpc/lib/server.makeJSONRPCHandler.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/handlers.go:152 +0xab7 net/http.HandlerFunc.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:1918 +0x51 net/http.(*ServeMux).ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:2254 +0xa2 github.com/tendermint/tendermint/rpc/lib/server.RecoverAndLogHandler.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:138 +0x4fa net/http.HandlerFunc.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:1918 +0x51 net/http.serverHandler.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:2619 +0xbc net/http.(*conn).serve() /usr/lib/go-1.9/src/net/http/server.go:1801 +0x83b Goroutine 23 (running) created at: github.com/tendermint/tendermint/consensus.(*ConsensusState).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:250 +0x35b github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/consensus.(*ConsensusReactor).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/reactor.go:69 +0x1b4 github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/consensus.(*ConsensusReactor).Start() <autogenerated>:1 +0x43 github.com/tendermint/tendermint/p2p.(*Switch).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch.go:177 +0x124 github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/node.(*Node).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/node/node.go:416 +0xa1b github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/rpc/test.StartTendermint() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/test/helpers.go:100 +0x5b github.com/tendermint/tendermint/rpc/client_test.TestMain() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/client/main_test.go:17 +0x4c main.main() github.com/tendermint/tendermint/rpc/client/_test/_testmain.go:76 +0x1cd Goroutine 47 (running) created at: net/http.(*Server).Serve() /usr/lib/go-1.9/src/net/http/server.go:2720 +0x37c net/http.Serve() /usr/lib/go-1.9/src/net/http/server.go:2323 +0xe2 github.com/tendermint/tendermint/rpc/lib/server.StartHTTPServer.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:35 +0xb3 ```
7 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
10 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
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
9 years ago
9 years ago
8 years ago
9 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
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
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
10 years ago
10 years ago
10 years ago
10 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
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 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
7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
8 years ago
10 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
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 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
10 years ago
10 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
10 years ago
10 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
10 years ago
10 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
10 years ago
9 years ago
7 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
7 years ago
10 years ago
7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
10 years ago
10 years ago
7 years ago
7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 years ago
9 years ago
8 years ago
9 years ago
7 years ago
10 years ago
10 years ago
  1. package consensus
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "reflect"
  7. "runtime/debug"
  8. "sync"
  9. "time"
  10. fail "github.com/ebuchman/fail-test"
  11. cmn "github.com/tendermint/tendermint/libs/common"
  12. "github.com/tendermint/tendermint/libs/log"
  13. cfg "github.com/tendermint/tendermint/config"
  14. cstypes "github.com/tendermint/tendermint/consensus/types"
  15. tmevents "github.com/tendermint/tendermint/libs/events"
  16. "github.com/tendermint/tendermint/p2p"
  17. sm "github.com/tendermint/tendermint/state"
  18. "github.com/tendermint/tendermint/types"
  19. )
  20. //-----------------------------------------------------------------------------
  21. // Config
  22. const (
  23. proposalHeartbeatIntervalSeconds = 2
  24. )
  25. //-----------------------------------------------------------------------------
  26. // Errors
  27. var (
  28. ErrInvalidProposalSignature = errors.New("Error invalid proposal signature")
  29. ErrInvalidProposalPOLRound = errors.New("Error invalid proposal POL round")
  30. ErrAddingVote = errors.New("Error adding vote")
  31. ErrVoteHeightMismatch = errors.New("Error vote height mismatch")
  32. )
  33. //-----------------------------------------------------------------------------
  34. var (
  35. msgQueueSize = 1000
  36. )
  37. // msgs from the reactor which may update the state
  38. type msgInfo struct {
  39. Msg ConsensusMessage `json:"msg"`
  40. PeerID p2p.ID `json:"peer_key"`
  41. }
  42. // internally generated messages which may update the state
  43. type timeoutInfo struct {
  44. Duration time.Duration `json:"duration"`
  45. Height int64 `json:"height"`
  46. Round int `json:"round"`
  47. Step cstypes.RoundStepType `json:"step"`
  48. }
  49. func (ti *timeoutInfo) String() string {
  50. return fmt.Sprintf("%v ; %d/%d %v", ti.Duration, ti.Height, ti.Round, ti.Step)
  51. }
  52. // ConsensusState handles execution of the consensus algorithm.
  53. // It processes votes and proposals, and upon reaching agreement,
  54. // commits blocks to the chain and executes them against the application.
  55. // The internal state machine receives input from peers, the internal validator, and from a timer.
  56. type ConsensusState struct {
  57. cmn.BaseService
  58. // config details
  59. config *cfg.ConsensusConfig
  60. privValidator types.PrivValidator // for signing votes
  61. // services for creating and executing blocks
  62. blockExec *sm.BlockExecutor
  63. blockStore sm.BlockStore
  64. mempool sm.Mempool
  65. evpool sm.EvidencePool
  66. // internal state
  67. mtx sync.RWMutex
  68. cstypes.RoundState
  69. state sm.State // State until height-1.
  70. // state changes may be triggered by: msgs from peers,
  71. // msgs from ourself, or by timeouts
  72. peerMsgQueue chan msgInfo
  73. internalMsgQueue chan msgInfo
  74. timeoutTicker TimeoutTicker
  75. // we use eventBus to trigger msg broadcasts in the reactor,
  76. // and to notify external subscribers, eg. through a websocket
  77. eventBus *types.EventBus
  78. // a Write-Ahead Log ensures we can recover from any kind of crash
  79. // and helps us avoid signing conflicting votes
  80. wal WAL
  81. replayMode bool // so we don't log signing errors during replay
  82. doWALCatchup bool // determines if we even try to do the catchup
  83. // for tests where we want to limit the number of transitions the state makes
  84. nSteps int
  85. // some functions can be overwritten for testing
  86. decideProposal func(height int64, round int)
  87. doPrevote func(height int64, round int)
  88. setProposal func(proposal *types.Proposal) error
  89. // closed when we finish shutting down
  90. done chan struct{}
  91. // synchronous pubsub between consensus state and reactor.
  92. // state only emits EventNewRoundStep, EventVote and EventProposalHeartbeat
  93. evsw tmevents.EventSwitch
  94. // for reporting metrics
  95. metrics *Metrics
  96. }
  97. // CSOption sets an optional parameter on the ConsensusState.
  98. type CSOption func(*ConsensusState)
  99. // NewConsensusState returns a new ConsensusState.
  100. func NewConsensusState(
  101. config *cfg.ConsensusConfig,
  102. state sm.State,
  103. blockExec *sm.BlockExecutor,
  104. blockStore sm.BlockStore,
  105. mempool sm.Mempool,
  106. evpool sm.EvidencePool,
  107. options ...CSOption,
  108. ) *ConsensusState {
  109. cs := &ConsensusState{
  110. config: config,
  111. blockExec: blockExec,
  112. blockStore: blockStore,
  113. mempool: mempool,
  114. peerMsgQueue: make(chan msgInfo, msgQueueSize),
  115. internalMsgQueue: make(chan msgInfo, msgQueueSize),
  116. timeoutTicker: NewTimeoutTicker(),
  117. done: make(chan struct{}),
  118. doWALCatchup: true,
  119. wal: nilWAL{},
  120. evpool: evpool,
  121. evsw: tmevents.NewEventSwitch(),
  122. metrics: NopMetrics(),
  123. }
  124. // set function defaults (may be overwritten before calling Start)
  125. cs.decideProposal = cs.defaultDecideProposal
  126. cs.doPrevote = cs.defaultDoPrevote
  127. cs.setProposal = cs.defaultSetProposal
  128. cs.updateToState(state)
  129. // Don't call scheduleRound0 yet.
  130. // We do that upon Start().
  131. cs.reconstructLastCommit(state)
  132. cs.BaseService = *cmn.NewBaseService(nil, "ConsensusState", cs)
  133. for _, option := range options {
  134. option(cs)
  135. }
  136. return cs
  137. }
  138. //----------------------------------------
  139. // Public interface
  140. // SetLogger implements Service.
  141. func (cs *ConsensusState) SetLogger(l log.Logger) {
  142. cs.BaseService.Logger = l
  143. cs.timeoutTicker.SetLogger(l)
  144. }
  145. // SetEventBus sets event bus.
  146. func (cs *ConsensusState) SetEventBus(b *types.EventBus) {
  147. cs.eventBus = b
  148. cs.blockExec.SetEventBus(b)
  149. }
  150. // WithMetrics sets the metrics.
  151. func WithMetrics(metrics *Metrics) CSOption {
  152. return func(cs *ConsensusState) { cs.metrics = metrics }
  153. }
  154. // String returns a string.
  155. func (cs *ConsensusState) String() string {
  156. // better not to access shared variables
  157. return fmt.Sprintf("ConsensusState") //(H:%v R:%v S:%v", cs.Height, cs.Round, cs.Step)
  158. }
  159. // GetState returns a copy of the chain state.
  160. func (cs *ConsensusState) GetState() sm.State {
  161. cs.mtx.RLock()
  162. defer cs.mtx.RUnlock()
  163. return cs.state.Copy()
  164. }
  165. // GetLastHeight returns the last height committed.
  166. // If there were no blocks, returns 0.
  167. func (cs *ConsensusState) GetLastHeight() int64 {
  168. cs.mtx.Lock()
  169. defer cs.mtx.Unlock()
  170. return cs.RoundState.Height - 1
  171. }
  172. // GetRoundState returns a shallow copy of the internal consensus state.
  173. func (cs *ConsensusState) GetRoundState() *cstypes.RoundState {
  174. cs.mtx.RLock()
  175. defer cs.mtx.RUnlock()
  176. rs := cs.RoundState // copy
  177. return &rs
  178. }
  179. // GetRoundStateJSON returns a json of RoundState, marshalled using go-amino.
  180. func (cs *ConsensusState) GetRoundStateJSON() ([]byte, error) {
  181. cs.mtx.RLock()
  182. defer cs.mtx.RUnlock()
  183. return cdc.MarshalJSON(cs.RoundState)
  184. }
  185. // GetRoundStateSimpleJSON returns a json of RoundStateSimple, marshalled using go-amino.
  186. func (cs *ConsensusState) GetRoundStateSimpleJSON() ([]byte, error) {
  187. cs.mtx.RLock()
  188. defer cs.mtx.RUnlock()
  189. return cdc.MarshalJSON(cs.RoundState.RoundStateSimple())
  190. }
  191. // GetValidators returns a copy of the current validators.
  192. func (cs *ConsensusState) GetValidators() (int64, []*types.Validator) {
  193. cs.mtx.RLock()
  194. defer cs.mtx.RUnlock()
  195. return cs.state.LastBlockHeight, cs.state.Validators.Copy().Validators
  196. }
  197. // SetPrivValidator sets the private validator account for signing votes.
  198. func (cs *ConsensusState) SetPrivValidator(priv types.PrivValidator) {
  199. cs.mtx.Lock()
  200. defer cs.mtx.Unlock()
  201. cs.privValidator = priv
  202. }
  203. // SetTimeoutTicker sets the local timer. It may be useful to overwrite for testing.
  204. func (cs *ConsensusState) SetTimeoutTicker(timeoutTicker TimeoutTicker) {
  205. cs.mtx.Lock()
  206. defer cs.mtx.Unlock()
  207. cs.timeoutTicker = timeoutTicker
  208. }
  209. // LoadCommit loads the commit for a given height.
  210. func (cs *ConsensusState) LoadCommit(height int64) *types.Commit {
  211. cs.mtx.RLock()
  212. defer cs.mtx.RUnlock()
  213. if height == cs.blockStore.Height() {
  214. return cs.blockStore.LoadSeenCommit(height)
  215. }
  216. return cs.blockStore.LoadBlockCommit(height)
  217. }
  218. // OnStart implements cmn.Service.
  219. // It loads the latest state via the WAL, and starts the timeout and receive routines.
  220. func (cs *ConsensusState) OnStart() error {
  221. if err := cs.evsw.Start(); err != nil {
  222. return err
  223. }
  224. // we may set the WAL in testing before calling Start,
  225. // so only OpenWAL if its still the nilWAL
  226. if _, ok := cs.wal.(nilWAL); ok {
  227. walFile := cs.config.WalFile()
  228. wal, err := cs.OpenWAL(walFile)
  229. if err != nil {
  230. cs.Logger.Error("Error loading ConsensusState wal", "err", err.Error())
  231. return err
  232. }
  233. cs.wal = wal
  234. }
  235. // we need the timeoutRoutine for replay so
  236. // we don't block on the tick chan.
  237. // NOTE: we will get a build up of garbage go routines
  238. // firing on the tockChan until the receiveRoutine is started
  239. // to deal with them (by that point, at most one will be valid)
  240. if err := cs.timeoutTicker.Start(); err != nil {
  241. return err
  242. }
  243. // we may have lost some votes if the process crashed
  244. // reload from consensus log to catchup
  245. if cs.doWALCatchup {
  246. if err := cs.catchupReplay(cs.Height); err != nil {
  247. cs.Logger.Error("Error on catchup replay. Proceeding to start ConsensusState anyway", "err", err.Error())
  248. // NOTE: if we ever do return an error here,
  249. // make sure to stop the timeoutTicker
  250. }
  251. }
  252. // now start the receiveRoutine
  253. go cs.receiveRoutine(0)
  254. // schedule the first round!
  255. // use GetRoundState so we don't race the receiveRoutine for access
  256. cs.scheduleRound0(cs.GetRoundState())
  257. return nil
  258. }
  259. // timeoutRoutine: receive requests for timeouts on tickChan and fire timeouts on tockChan
  260. // receiveRoutine: serializes processing of proposoals, block parts, votes; coordinates state transitions
  261. func (cs *ConsensusState) startRoutines(maxSteps int) {
  262. err := cs.timeoutTicker.Start()
  263. if err != nil {
  264. cs.Logger.Error("Error starting timeout ticker", "err", err)
  265. return
  266. }
  267. go cs.receiveRoutine(maxSteps)
  268. }
  269. // OnStop implements cmn.Service. It stops all routines and waits for the WAL to finish.
  270. func (cs *ConsensusState) OnStop() {
  271. cs.evsw.Stop()
  272. cs.timeoutTicker.Stop()
  273. }
  274. // Wait waits for the the main routine to return.
  275. // NOTE: be sure to Stop() the event switch and drain
  276. // any event channels or this may deadlock
  277. func (cs *ConsensusState) Wait() {
  278. <-cs.done
  279. }
  280. // OpenWAL opens a file to log all consensus messages and timeouts for deterministic accountability
  281. func (cs *ConsensusState) OpenWAL(walFile string) (WAL, error) {
  282. wal, err := NewWAL(walFile)
  283. if err != nil {
  284. cs.Logger.Error("Failed to open WAL for consensus state", "wal", walFile, "err", err)
  285. return nil, err
  286. }
  287. wal.SetLogger(cs.Logger.With("wal", walFile))
  288. if err := wal.Start(); err != nil {
  289. return nil, err
  290. }
  291. return wal, nil
  292. }
  293. //------------------------------------------------------------
  294. // Public interface for passing messages into the consensus state, possibly causing a state transition.
  295. // If peerID == "", the msg is considered internal.
  296. // Messages are added to the appropriate queue (peer or internal).
  297. // If the queue is full, the function may block.
  298. // TODO: should these return anything or let callers just use events?
  299. // AddVote inputs a vote.
  300. func (cs *ConsensusState) AddVote(vote *types.Vote, peerID p2p.ID) (added bool, err error) {
  301. if peerID == "" {
  302. cs.internalMsgQueue <- msgInfo{&VoteMessage{vote}, ""}
  303. } else {
  304. cs.peerMsgQueue <- msgInfo{&VoteMessage{vote}, peerID}
  305. }
  306. // TODO: wait for event?!
  307. return false, nil
  308. }
  309. // SetProposal inputs a proposal.
  310. func (cs *ConsensusState) SetProposal(proposal *types.Proposal, peerID p2p.ID) error {
  311. if peerID == "" {
  312. cs.internalMsgQueue <- msgInfo{&ProposalMessage{proposal}, ""}
  313. } else {
  314. cs.peerMsgQueue <- msgInfo{&ProposalMessage{proposal}, peerID}
  315. }
  316. // TODO: wait for event?!
  317. return nil
  318. }
  319. // AddProposalBlockPart inputs a part of the proposal block.
  320. func (cs *ConsensusState) AddProposalBlockPart(height int64, round int, part *types.Part, peerID p2p.ID) error {
  321. if peerID == "" {
  322. cs.internalMsgQueue <- msgInfo{&BlockPartMessage{height, round, part}, ""}
  323. } else {
  324. cs.peerMsgQueue <- msgInfo{&BlockPartMessage{height, round, part}, peerID}
  325. }
  326. // TODO: wait for event?!
  327. return nil
  328. }
  329. // SetProposalAndBlock inputs the proposal and all block parts.
  330. func (cs *ConsensusState) SetProposalAndBlock(proposal *types.Proposal, block *types.Block, parts *types.PartSet, peerID p2p.ID) error {
  331. if err := cs.SetProposal(proposal, peerID); err != nil {
  332. return err
  333. }
  334. for i := 0; i < parts.Total(); i++ {
  335. part := parts.GetPart(i)
  336. if err := cs.AddProposalBlockPart(proposal.Height, proposal.Round, part, peerID); err != nil {
  337. return err
  338. }
  339. }
  340. return nil
  341. }
  342. //------------------------------------------------------------
  343. // internal functions for managing the state
  344. func (cs *ConsensusState) updateHeight(height int64) {
  345. cs.metrics.Height.Set(float64(height))
  346. cs.Height = height
  347. }
  348. func (cs *ConsensusState) updateRoundStep(round int, step cstypes.RoundStepType) {
  349. cs.Round = round
  350. cs.Step = step
  351. }
  352. // enterNewRound(height, 0) at cs.StartTime.
  353. func (cs *ConsensusState) scheduleRound0(rs *cstypes.RoundState) {
  354. //cs.Logger.Info("scheduleRound0", "now", time.Now(), "startTime", cs.StartTime)
  355. sleepDuration := rs.StartTime.Sub(time.Now()) // nolint: gotype, gosimple
  356. cs.scheduleTimeout(sleepDuration, rs.Height, 0, cstypes.RoundStepNewHeight)
  357. }
  358. // Attempt to schedule a timeout (by sending timeoutInfo on the tickChan)
  359. func (cs *ConsensusState) scheduleTimeout(duration time.Duration, height int64, round int, step cstypes.RoundStepType) {
  360. cs.timeoutTicker.ScheduleTimeout(timeoutInfo{duration, height, round, step})
  361. }
  362. // send a msg into the receiveRoutine regarding our own proposal, block part, or vote
  363. func (cs *ConsensusState) sendInternalMessage(mi msgInfo) {
  364. select {
  365. case cs.internalMsgQueue <- mi:
  366. default:
  367. // NOTE: using the go-routine means our votes can
  368. // be processed out of order.
  369. // TODO: use CList here for strict determinism and
  370. // attempt push to internalMsgQueue in receiveRoutine
  371. cs.Logger.Info("Internal msg queue is full. Using a go-routine")
  372. go func() { cs.internalMsgQueue <- mi }()
  373. }
  374. }
  375. // Reconstruct LastCommit from SeenCommit, which we saved along with the block,
  376. // (which happens even before saving the state)
  377. func (cs *ConsensusState) reconstructLastCommit(state sm.State) {
  378. if state.LastBlockHeight == 0 {
  379. return
  380. }
  381. seenCommit := cs.blockStore.LoadSeenCommit(state.LastBlockHeight)
  382. lastPrecommits := types.NewVoteSet(state.ChainID, state.LastBlockHeight, seenCommit.Round(), types.VoteTypePrecommit, state.LastValidators)
  383. for _, precommit := range seenCommit.Precommits {
  384. if precommit == nil {
  385. continue
  386. }
  387. added, err := lastPrecommits.AddVote(precommit)
  388. if !added || err != nil {
  389. cmn.PanicCrisis(fmt.Sprintf("Failed to reconstruct LastCommit: %v", err))
  390. }
  391. }
  392. if !lastPrecommits.HasTwoThirdsMajority() {
  393. cmn.PanicSanity("Failed to reconstruct LastCommit: Does not have +2/3 maj")
  394. }
  395. cs.LastCommit = lastPrecommits
  396. }
  397. // Updates ConsensusState and increments height to match that of state.
  398. // The round becomes 0 and cs.Step becomes cstypes.RoundStepNewHeight.
  399. func (cs *ConsensusState) updateToState(state sm.State) {
  400. if cs.CommitRound > -1 && 0 < cs.Height && cs.Height != state.LastBlockHeight {
  401. cmn.PanicSanity(fmt.Sprintf("updateToState() expected state height of %v but found %v",
  402. cs.Height, state.LastBlockHeight))
  403. }
  404. if !cs.state.IsEmpty() && cs.state.LastBlockHeight+1 != cs.Height {
  405. // This might happen when someone else is mutating cs.state.
  406. // Someone forgot to pass in state.Copy() somewhere?!
  407. cmn.PanicSanity(fmt.Sprintf("Inconsistent cs.state.LastBlockHeight+1 %v vs cs.Height %v",
  408. cs.state.LastBlockHeight+1, cs.Height))
  409. }
  410. // If state isn't further out than cs.state, just ignore.
  411. // This happens when SwitchToConsensus() is called in the reactor.
  412. // We don't want to reset e.g. the Votes, but we still want to
  413. // signal the new round step, because other services (eg. mempool)
  414. // depend on having an up-to-date peer state!
  415. if !cs.state.IsEmpty() && (state.LastBlockHeight <= cs.state.LastBlockHeight) {
  416. cs.Logger.Info("Ignoring updateToState()", "newHeight", state.LastBlockHeight+1, "oldHeight", cs.state.LastBlockHeight+1)
  417. cs.newStep()
  418. return
  419. }
  420. // Reset fields based on state.
  421. validators := state.Validators
  422. lastPrecommits := (*types.VoteSet)(nil)
  423. if cs.CommitRound > -1 && cs.Votes != nil {
  424. if !cs.Votes.Precommits(cs.CommitRound).HasTwoThirdsMajority() {
  425. cmn.PanicSanity("updateToState(state) called but last Precommit round didn't have +2/3")
  426. }
  427. lastPrecommits = cs.Votes.Precommits(cs.CommitRound)
  428. }
  429. // Next desired block height
  430. height := state.LastBlockHeight + 1
  431. // RoundState fields
  432. cs.updateHeight(height)
  433. cs.updateRoundStep(0, cstypes.RoundStepNewHeight)
  434. if cs.CommitTime.IsZero() {
  435. // "Now" makes it easier to sync up dev nodes.
  436. // We add timeoutCommit to allow transactions
  437. // to be gathered for the first block.
  438. // And alternative solution that relies on clocks:
  439. // cs.StartTime = state.LastBlockTime.Add(timeoutCommit)
  440. cs.StartTime = cs.config.Commit(time.Now())
  441. } else {
  442. cs.StartTime = cs.config.Commit(cs.CommitTime)
  443. }
  444. cs.Validators = validators
  445. cs.Proposal = nil
  446. cs.ProposalBlock = nil
  447. cs.ProposalBlockParts = nil
  448. cs.LockedRound = 0
  449. cs.LockedBlock = nil
  450. cs.LockedBlockParts = nil
  451. cs.ValidRound = 0
  452. cs.ValidBlock = nil
  453. cs.ValidBlockParts = nil
  454. cs.Votes = cstypes.NewHeightVoteSet(state.ChainID, height, validators)
  455. cs.CommitRound = -1
  456. cs.LastCommit = lastPrecommits
  457. cs.LastValidators = state.LastValidators
  458. cs.state = state
  459. // Finally, broadcast RoundState
  460. cs.newStep()
  461. }
  462. func (cs *ConsensusState) newStep() {
  463. rs := cs.RoundStateEvent()
  464. cs.wal.Write(rs)
  465. cs.nSteps++
  466. // newStep is called by updateToState in NewConsensusState before the eventBus is set!
  467. if cs.eventBus != nil {
  468. cs.eventBus.PublishEventNewRoundStep(rs)
  469. cs.evsw.FireEvent(types.EventNewRoundStep, &cs.RoundState)
  470. }
  471. }
  472. //-----------------------------------------
  473. // the main go routines
  474. // receiveRoutine handles messages which may cause state transitions.
  475. // it's argument (n) is the number of messages to process before exiting - use 0 to run forever
  476. // It keeps the RoundState and is the only thing that updates it.
  477. // Updates (state transitions) happen on timeouts, complete proposals, and 2/3 majorities.
  478. // ConsensusState must be locked before any internal state is updated.
  479. func (cs *ConsensusState) receiveRoutine(maxSteps int) {
  480. onExit := func(cs *ConsensusState) {
  481. // NOTE: the internalMsgQueue may have signed messages from our
  482. // priv_val that haven't hit the WAL, but its ok because
  483. // priv_val tracks LastSig
  484. // close wal now that we're done writing to it
  485. cs.wal.Stop()
  486. cs.wal.Wait()
  487. close(cs.done)
  488. }
  489. defer func() {
  490. if r := recover(); r != nil {
  491. cs.Logger.Error("CONSENSUS FAILURE!!!", "err", r, "stack", string(debug.Stack()))
  492. // stop gracefully
  493. //
  494. // NOTE: We most probably shouldn't be running any further when there is
  495. // some unexpected panic. Some unknown error happened, and so we don't
  496. // know if that will result in the validator signing an invalid thing. It
  497. // might be worthwhile to explore a mechanism for manual resuming via
  498. // some console or secure RPC system, but for now, halting the chain upon
  499. // unexpected consensus bugs sounds like the better option.
  500. onExit(cs)
  501. }
  502. }()
  503. for {
  504. if maxSteps > 0 {
  505. if cs.nSteps >= maxSteps {
  506. cs.Logger.Info("reached max steps. exiting receive routine")
  507. cs.nSteps = 0
  508. return
  509. }
  510. }
  511. rs := cs.RoundState
  512. var mi msgInfo
  513. select {
  514. case <-cs.mempool.TxsAvailable():
  515. cs.handleTxsAvailable()
  516. case mi = <-cs.peerMsgQueue:
  517. cs.wal.Write(mi)
  518. // handles proposals, block parts, votes
  519. // may generate internal events (votes, complete proposals, 2/3 majorities)
  520. cs.handleMsg(mi)
  521. case mi = <-cs.internalMsgQueue:
  522. cs.wal.WriteSync(mi) // NOTE: fsync
  523. // handles proposals, block parts, votes
  524. cs.handleMsg(mi)
  525. case ti := <-cs.timeoutTicker.Chan(): // tockChan:
  526. cs.wal.Write(ti)
  527. // if the timeout is relevant to the rs
  528. // go to the next step
  529. cs.handleTimeout(ti, rs)
  530. case <-cs.Quit():
  531. onExit(cs)
  532. return
  533. }
  534. }
  535. }
  536. // state transitions on complete-proposal, 2/3-any, 2/3-one
  537. func (cs *ConsensusState) handleMsg(mi msgInfo) {
  538. cs.mtx.Lock()
  539. defer cs.mtx.Unlock()
  540. var err error
  541. msg, peerID := mi.Msg, mi.PeerID
  542. switch msg := msg.(type) {
  543. case *ProposalMessage:
  544. // will not cause transition.
  545. // once proposal is set, we can receive block parts
  546. err = cs.setProposal(msg.Proposal)
  547. case *BlockPartMessage:
  548. // if the proposal is complete, we'll enterPrevote or tryFinalizeCommit
  549. _, err = cs.addProposalBlockPart(msg, peerID)
  550. if err != nil && msg.Round != cs.Round {
  551. cs.Logger.Debug("Received block part from wrong round", "height", cs.Height, "csRound", cs.Round, "blockRound", msg.Round)
  552. err = nil
  553. }
  554. case *VoteMessage:
  555. // attempt to add the vote and dupeout the validator if its a duplicate signature
  556. // if the vote gives us a 2/3-any or 2/3-one, we transition
  557. err := cs.tryAddVote(msg.Vote, peerID)
  558. if err == ErrAddingVote {
  559. // TODO: punish peer
  560. // We probably don't want to stop the peer here. The vote does not
  561. // necessarily comes from a malicious peer but can be just broadcasted by
  562. // a typical peer.
  563. // https://github.com/tendermint/tendermint/issues/1281
  564. }
  565. // NOTE: the vote is broadcast to peers by the reactor listening
  566. // for vote events
  567. // TODO: If rs.Height == vote.Height && rs.Round < vote.Round,
  568. // the peer is sending us CatchupCommit precommits.
  569. // We could make note of this and help filter in broadcastHasVoteMessage().
  570. default:
  571. cs.Logger.Error("Unknown msg type", reflect.TypeOf(msg))
  572. }
  573. if err != nil {
  574. cs.Logger.Error("Error with msg", "height", cs.Height, "round", cs.Round, "type", reflect.TypeOf(msg), "peer", peerID, "err", err, "msg", msg)
  575. }
  576. }
  577. func (cs *ConsensusState) handleTimeout(ti timeoutInfo, rs cstypes.RoundState) {
  578. cs.Logger.Debug("Received tock", "timeout", ti.Duration, "height", ti.Height, "round", ti.Round, "step", ti.Step)
  579. // timeouts must be for current height, round, step
  580. if ti.Height != rs.Height || ti.Round < rs.Round || (ti.Round == rs.Round && ti.Step < rs.Step) {
  581. cs.Logger.Debug("Ignoring tock because we're ahead", "height", rs.Height, "round", rs.Round, "step", rs.Step)
  582. return
  583. }
  584. // the timeout will now cause a state transition
  585. cs.mtx.Lock()
  586. defer cs.mtx.Unlock()
  587. switch ti.Step {
  588. case cstypes.RoundStepNewHeight:
  589. // NewRound event fired from enterNewRound.
  590. // XXX: should we fire timeout here (for timeout commit)?
  591. cs.enterNewRound(ti.Height, 0)
  592. case cstypes.RoundStepNewRound:
  593. cs.enterPropose(ti.Height, 0)
  594. case cstypes.RoundStepPropose:
  595. cs.eventBus.PublishEventTimeoutPropose(cs.RoundStateEvent())
  596. cs.enterPrevote(ti.Height, ti.Round)
  597. case cstypes.RoundStepPrevoteWait:
  598. cs.eventBus.PublishEventTimeoutWait(cs.RoundStateEvent())
  599. cs.enterPrecommit(ti.Height, ti.Round)
  600. case cstypes.RoundStepPrecommitWait:
  601. cs.eventBus.PublishEventTimeoutWait(cs.RoundStateEvent())
  602. cs.enterNewRound(ti.Height, ti.Round+1)
  603. default:
  604. panic(fmt.Sprintf("Invalid timeout step: %v", ti.Step))
  605. }
  606. }
  607. func (cs *ConsensusState) handleTxsAvailable() {
  608. cs.mtx.Lock()
  609. defer cs.mtx.Unlock()
  610. // we only need to do this for round 0
  611. cs.enterPropose(cs.Height, 0)
  612. }
  613. //-----------------------------------------------------------------------------
  614. // State functions
  615. // Used internally by handleTimeout and handleMsg to make state transitions
  616. // Enter: `timeoutNewHeight` by startTime (commitTime+timeoutCommit),
  617. // or, if SkipTimeout==true, after receiving all precommits from (height,round-1)
  618. // Enter: `timeoutPrecommits` after any +2/3 precommits from (height,round-1)
  619. // Enter: +2/3 precommits for nil at (height,round-1)
  620. // Enter: +2/3 prevotes any or +2/3 precommits for block or any from (height, round)
  621. // NOTE: cs.StartTime was already set for height.
  622. func (cs *ConsensusState) enterNewRound(height int64, round int) {
  623. logger := cs.Logger.With("height", height, "round", round)
  624. if cs.Height != height || round < cs.Round || (cs.Round == round && cs.Step != cstypes.RoundStepNewHeight) {
  625. logger.Debug(fmt.Sprintf("enterNewRound(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  626. return
  627. }
  628. if now := time.Now(); cs.StartTime.After(now) {
  629. logger.Info("Need to set a buffer and log message here for sanity.", "startTime", cs.StartTime, "now", now)
  630. }
  631. logger.Info(fmt.Sprintf("enterNewRound(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  632. // Increment validators if necessary
  633. validators := cs.Validators
  634. if cs.Round < round {
  635. validators = validators.Copy()
  636. validators.IncrementAccum(round - cs.Round)
  637. }
  638. // Setup new round
  639. // we don't fire newStep for this step,
  640. // but we fire an event, so update the round step first
  641. cs.updateRoundStep(round, cstypes.RoundStepNewRound)
  642. cs.Validators = validators
  643. if round == 0 {
  644. // We've already reset these upon new height,
  645. // and meanwhile we might have received a proposal
  646. // for round 0.
  647. } else {
  648. logger.Info("Resetting Proposal info")
  649. cs.Proposal = nil
  650. cs.ProposalBlock = nil
  651. cs.ProposalBlockParts = nil
  652. }
  653. cs.Votes.SetRound(round + 1) // also track next round (round+1) to allow round-skipping
  654. cs.eventBus.PublishEventNewRound(cs.RoundStateEvent())
  655. cs.metrics.Rounds.Set(float64(round))
  656. // Wait for txs to be available in the mempool
  657. // before we enterPropose in round 0. If the last block changed the app hash,
  658. // we may need an empty "proof" block, and enterPropose immediately.
  659. waitForTxs := cs.config.WaitForTxs() && round == 0 && !cs.needProofBlock(height)
  660. if waitForTxs {
  661. if cs.config.CreateEmptyBlocksInterval > 0 {
  662. cs.scheduleTimeout(cs.config.EmptyBlocksInterval(), height, round, cstypes.RoundStepNewRound)
  663. }
  664. go cs.proposalHeartbeat(height, round)
  665. } else {
  666. cs.enterPropose(height, round)
  667. }
  668. }
  669. // needProofBlock returns true on the first height (so the genesis app hash is signed right away)
  670. // and where the last block (height-1) caused the app hash to change
  671. func (cs *ConsensusState) needProofBlock(height int64) bool {
  672. if height == 1 {
  673. return true
  674. }
  675. lastBlockMeta := cs.blockStore.LoadBlockMeta(height - 1)
  676. return !bytes.Equal(cs.state.AppHash, lastBlockMeta.Header.AppHash)
  677. }
  678. func (cs *ConsensusState) proposalHeartbeat(height int64, round int) {
  679. counter := 0
  680. addr := cs.privValidator.GetAddress()
  681. valIndex, _ := cs.Validators.GetByAddress(addr)
  682. chainID := cs.state.ChainID
  683. for {
  684. rs := cs.GetRoundState()
  685. // if we've already moved on, no need to send more heartbeats
  686. if rs.Step > cstypes.RoundStepNewRound || rs.Round > round || rs.Height > height {
  687. return
  688. }
  689. heartbeat := &types.Heartbeat{
  690. Height: rs.Height,
  691. Round: rs.Round,
  692. Sequence: counter,
  693. ValidatorAddress: addr,
  694. ValidatorIndex: valIndex,
  695. }
  696. cs.privValidator.SignHeartbeat(chainID, heartbeat)
  697. cs.eventBus.PublishEventProposalHeartbeat(types.EventDataProposalHeartbeat{heartbeat})
  698. cs.evsw.FireEvent(types.EventProposalHeartbeat, heartbeat)
  699. counter++
  700. time.Sleep(proposalHeartbeatIntervalSeconds * time.Second)
  701. }
  702. }
  703. // Enter (CreateEmptyBlocks): from enterNewRound(height,round)
  704. // Enter (CreateEmptyBlocks, CreateEmptyBlocksInterval > 0 ): after enterNewRound(height,round), after timeout of CreateEmptyBlocksInterval
  705. // Enter (!CreateEmptyBlocks) : after enterNewRound(height,round), once txs are in the mempool
  706. func (cs *ConsensusState) enterPropose(height int64, round int) {
  707. logger := cs.Logger.With("height", height, "round", round)
  708. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPropose <= cs.Step) {
  709. logger.Debug(fmt.Sprintf("enterPropose(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  710. return
  711. }
  712. logger.Info(fmt.Sprintf("enterPropose(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  713. defer func() {
  714. // Done enterPropose:
  715. cs.updateRoundStep(round, cstypes.RoundStepPropose)
  716. cs.newStep()
  717. // If we have the whole proposal + POL, then goto Prevote now.
  718. // else, we'll enterPrevote when the rest of the proposal is received (in AddProposalBlockPart),
  719. // or else after timeoutPropose
  720. if cs.isProposalComplete() {
  721. cs.enterPrevote(height, cs.Round)
  722. }
  723. }()
  724. // If we don't get the proposal and all block parts quick enough, enterPrevote
  725. cs.scheduleTimeout(cs.config.Propose(round), height, round, cstypes.RoundStepPropose)
  726. // Nothing more to do if we're not a validator
  727. if cs.privValidator == nil {
  728. logger.Debug("This node is not a validator")
  729. return
  730. }
  731. // if not a validator, we're done
  732. if !cs.Validators.HasAddress(cs.privValidator.GetAddress()) {
  733. logger.Debug("This node is not a validator", "addr", cs.privValidator.GetAddress(), "vals", cs.Validators)
  734. return
  735. }
  736. logger.Debug("This node is a validator")
  737. if cs.isProposer() {
  738. logger.Info("enterPropose: Our turn to propose", "proposer", cs.Validators.GetProposer().Address, "privValidator", cs.privValidator)
  739. cs.decideProposal(height, round)
  740. } else {
  741. logger.Info("enterPropose: Not our turn to propose", "proposer", cs.Validators.GetProposer().Address, "privValidator", cs.privValidator)
  742. }
  743. }
  744. func (cs *ConsensusState) isProposer() bool {
  745. return bytes.Equal(cs.Validators.GetProposer().Address, cs.privValidator.GetAddress())
  746. }
  747. func (cs *ConsensusState) defaultDecideProposal(height int64, round int) {
  748. var block *types.Block
  749. var blockParts *types.PartSet
  750. // Decide on block
  751. if cs.LockedBlock != nil {
  752. // If we're locked onto a block, just choose that.
  753. block, blockParts = cs.LockedBlock, cs.LockedBlockParts
  754. } else if cs.ValidBlock != nil {
  755. // If there is valid block, choose that.
  756. block, blockParts = cs.ValidBlock, cs.ValidBlockParts
  757. } else {
  758. // Create a new proposal block from state/txs from the mempool.
  759. block, blockParts = cs.createProposalBlock()
  760. if block == nil { // on error
  761. return
  762. }
  763. }
  764. // Make proposal
  765. polRound, polBlockID := cs.Votes.POLInfo()
  766. proposal := types.NewProposal(height, round, blockParts.Header(), polRound, polBlockID)
  767. if err := cs.privValidator.SignProposal(cs.state.ChainID, proposal); err == nil {
  768. // Set fields
  769. /* fields set by setProposal and addBlockPart
  770. cs.Proposal = proposal
  771. cs.ProposalBlock = block
  772. cs.ProposalBlockParts = blockParts
  773. */
  774. // send proposal and block parts on internal msg queue
  775. cs.sendInternalMessage(msgInfo{&ProposalMessage{proposal}, ""})
  776. for i := 0; i < blockParts.Total(); i++ {
  777. part := blockParts.GetPart(i)
  778. cs.sendInternalMessage(msgInfo{&BlockPartMessage{cs.Height, cs.Round, part}, ""})
  779. }
  780. cs.Logger.Info("Signed proposal", "height", height, "round", round, "proposal", proposal)
  781. cs.Logger.Debug(fmt.Sprintf("Signed proposal block: %v", block))
  782. } else {
  783. if !cs.replayMode {
  784. cs.Logger.Error("enterPropose: Error signing proposal", "height", height, "round", round, "err", err)
  785. }
  786. }
  787. }
  788. // Returns true if the proposal block is complete &&
  789. // (if POLRound was proposed, we have +2/3 prevotes from there).
  790. func (cs *ConsensusState) isProposalComplete() bool {
  791. if cs.Proposal == nil || cs.ProposalBlock == nil {
  792. return false
  793. }
  794. // we have the proposal. if there's a POLRound,
  795. // make sure we have the prevotes from it too
  796. if cs.Proposal.POLRound < 0 {
  797. return true
  798. }
  799. // if this is false the proposer is lying or we haven't received the POL yet
  800. return cs.Votes.Prevotes(cs.Proposal.POLRound).HasTwoThirdsMajority()
  801. }
  802. // Create the next block to propose and return it.
  803. // We really only need to return the parts, but the block
  804. // is returned for convenience so we can log the proposal block.
  805. // Returns nil block upon error.
  806. // NOTE: keep it side-effect free for clarity.
  807. func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts *types.PartSet) {
  808. var commit *types.Commit
  809. if cs.Height == 1 {
  810. // We're creating a proposal for the first block.
  811. // The commit is empty, but not nil.
  812. commit = &types.Commit{}
  813. } else if cs.LastCommit.HasTwoThirdsMajority() {
  814. // Make the commit from LastCommit
  815. commit = cs.LastCommit.MakeCommit()
  816. } else {
  817. // This shouldn't happen.
  818. cs.Logger.Error("enterPropose: Cannot propose anything: No commit for the previous block.")
  819. return
  820. }
  821. // Mempool validated transactions
  822. txs := cs.mempool.Reap(cs.state.ConsensusParams.BlockSize.MaxTxs)
  823. evidence := cs.evpool.PendingEvidence()
  824. proposerAddr := cs.privValidator.GetAddress()
  825. block, parts := cs.state.MakeBlock(cs.Height, txs, commit, evidence, proposerAddr)
  826. return block, parts
  827. }
  828. // Enter: `timeoutPropose` after entering Propose.
  829. // Enter: proposal block and POL is ready.
  830. // Enter: any +2/3 prevotes for future round.
  831. // Prevote for LockedBlock if we're locked, or ProposalBlock if valid.
  832. // Otherwise vote nil.
  833. func (cs *ConsensusState) enterPrevote(height int64, round int) {
  834. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrevote <= cs.Step) {
  835. cs.Logger.Debug(fmt.Sprintf("enterPrevote(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  836. return
  837. }
  838. defer func() {
  839. // Done enterPrevote:
  840. cs.updateRoundStep(round, cstypes.RoundStepPrevote)
  841. cs.newStep()
  842. }()
  843. // fire event for how we got here
  844. if cs.isProposalComplete() {
  845. cs.eventBus.PublishEventCompleteProposal(cs.RoundStateEvent())
  846. } else {
  847. // we received +2/3 prevotes for a future round
  848. // TODO: catchup event?
  849. }
  850. cs.Logger.Info(fmt.Sprintf("enterPrevote(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  851. // Sign and broadcast vote as necessary
  852. cs.doPrevote(height, round)
  853. // Once `addVote` hits any +2/3 prevotes, we will go to PrevoteWait
  854. // (so we have more time to try and collect +2/3 prevotes for a single block)
  855. }
  856. func (cs *ConsensusState) defaultDoPrevote(height int64, round int) {
  857. logger := cs.Logger.With("height", height, "round", round)
  858. // If a block is locked, prevote that.
  859. if cs.LockedBlock != nil {
  860. logger.Info("enterPrevote: Block was locked")
  861. cs.signAddVote(types.VoteTypePrevote, cs.LockedBlock.Hash(), cs.LockedBlockParts.Header())
  862. return
  863. }
  864. // If ProposalBlock is nil, prevote nil.
  865. if cs.ProposalBlock == nil {
  866. logger.Info("enterPrevote: ProposalBlock is nil")
  867. cs.signAddVote(types.VoteTypePrevote, nil, types.PartSetHeader{})
  868. return
  869. }
  870. // Validate proposal block
  871. err := cs.blockExec.ValidateBlock(cs.state, cs.ProposalBlock)
  872. if err != nil {
  873. // ProposalBlock is invalid, prevote nil.
  874. logger.Error("enterPrevote: ProposalBlock is invalid", "err", err)
  875. cs.signAddVote(types.VoteTypePrevote, nil, types.PartSetHeader{})
  876. return
  877. }
  878. // Prevote cs.ProposalBlock
  879. // NOTE: the proposal signature is validated when it is received,
  880. // and the proposal block parts are validated as they are received (against the merkle hash in the proposal)
  881. logger.Info("enterPrevote: ProposalBlock is valid")
  882. cs.signAddVote(types.VoteTypePrevote, cs.ProposalBlock.Hash(), cs.ProposalBlockParts.Header())
  883. }
  884. // Enter: any +2/3 prevotes at next round.
  885. func (cs *ConsensusState) enterPrevoteWait(height int64, round int) {
  886. logger := cs.Logger.With("height", height, "round", round)
  887. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrevoteWait <= cs.Step) {
  888. logger.Debug(fmt.Sprintf("enterPrevoteWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  889. return
  890. }
  891. if !cs.Votes.Prevotes(round).HasTwoThirdsAny() {
  892. cmn.PanicSanity(fmt.Sprintf("enterPrevoteWait(%v/%v), but Prevotes does not have any +2/3 votes", height, round))
  893. }
  894. logger.Info(fmt.Sprintf("enterPrevoteWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  895. defer func() {
  896. // Done enterPrevoteWait:
  897. cs.updateRoundStep(round, cstypes.RoundStepPrevoteWait)
  898. cs.newStep()
  899. }()
  900. // Wait for some more prevotes; enterPrecommit
  901. cs.scheduleTimeout(cs.config.Prevote(round), height, round, cstypes.RoundStepPrevoteWait)
  902. }
  903. // Enter: `timeoutPrevote` after any +2/3 prevotes.
  904. // Enter: +2/3 precomits for block or nil.
  905. // Enter: any +2/3 precommits for next round.
  906. // Lock & precommit the ProposalBlock if we have enough prevotes for it (a POL in this round)
  907. // else, unlock an existing lock and precommit nil if +2/3 of prevotes were nil,
  908. // else, precommit nil otherwise.
  909. func (cs *ConsensusState) enterPrecommit(height int64, round int) {
  910. logger := cs.Logger.With("height", height, "round", round)
  911. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrecommit <= cs.Step) {
  912. logger.Debug(fmt.Sprintf("enterPrecommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  913. return
  914. }
  915. logger.Info(fmt.Sprintf("enterPrecommit(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  916. defer func() {
  917. // Done enterPrecommit:
  918. cs.updateRoundStep(round, cstypes.RoundStepPrecommit)
  919. cs.newStep()
  920. }()
  921. // check for a polka
  922. blockID, ok := cs.Votes.Prevotes(round).TwoThirdsMajority()
  923. // If we don't have a polka, we must precommit nil.
  924. if !ok {
  925. if cs.LockedBlock != nil {
  926. logger.Info("enterPrecommit: No +2/3 prevotes during enterPrecommit while we're locked. Precommitting nil")
  927. } else {
  928. logger.Info("enterPrecommit: No +2/3 prevotes during enterPrecommit. Precommitting nil.")
  929. }
  930. cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{})
  931. return
  932. }
  933. // At this point +2/3 prevoted for a particular block or nil.
  934. cs.eventBus.PublishEventPolka(cs.RoundStateEvent())
  935. // the latest POLRound should be this round.
  936. polRound, _ := cs.Votes.POLInfo()
  937. if polRound < round {
  938. cmn.PanicSanity(fmt.Sprintf("This POLRound should be %v but got %v", round, polRound))
  939. }
  940. // +2/3 prevoted nil. Unlock and precommit nil.
  941. if len(blockID.Hash) == 0 {
  942. if cs.LockedBlock == nil {
  943. logger.Info("enterPrecommit: +2/3 prevoted for nil.")
  944. } else {
  945. logger.Info("enterPrecommit: +2/3 prevoted for nil. Unlocking")
  946. cs.LockedRound = 0
  947. cs.LockedBlock = nil
  948. cs.LockedBlockParts = nil
  949. cs.eventBus.PublishEventUnlock(cs.RoundStateEvent())
  950. }
  951. cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{})
  952. return
  953. }
  954. // At this point, +2/3 prevoted for a particular block.
  955. // If we're already locked on that block, precommit it, and update the LockedRound
  956. if cs.LockedBlock.HashesTo(blockID.Hash) {
  957. logger.Info("enterPrecommit: +2/3 prevoted locked block. Relocking")
  958. cs.LockedRound = round
  959. cs.eventBus.PublishEventRelock(cs.RoundStateEvent())
  960. cs.signAddVote(types.VoteTypePrecommit, blockID.Hash, blockID.PartsHeader)
  961. return
  962. }
  963. // If +2/3 prevoted for proposal block, stage and precommit it
  964. if cs.ProposalBlock.HashesTo(blockID.Hash) {
  965. logger.Info("enterPrecommit: +2/3 prevoted proposal block. Locking", "hash", blockID.Hash)
  966. // Validate the block.
  967. if err := cs.blockExec.ValidateBlock(cs.state, cs.ProposalBlock); err != nil {
  968. cmn.PanicConsensus(fmt.Sprintf("enterPrecommit: +2/3 prevoted for an invalid block: %v", err))
  969. }
  970. cs.LockedRound = round
  971. cs.LockedBlock = cs.ProposalBlock
  972. cs.LockedBlockParts = cs.ProposalBlockParts
  973. cs.eventBus.PublishEventLock(cs.RoundStateEvent())
  974. cs.signAddVote(types.VoteTypePrecommit, blockID.Hash, blockID.PartsHeader)
  975. return
  976. }
  977. // There was a polka in this round for a block we don't have.
  978. // Fetch that block, unlock, and precommit nil.
  979. // The +2/3 prevotes for this round is the POL for our unlock.
  980. // TODO: In the future save the POL prevotes for justification.
  981. cs.LockedRound = 0
  982. cs.LockedBlock = nil
  983. cs.LockedBlockParts = nil
  984. if !cs.ProposalBlockParts.HasHeader(blockID.PartsHeader) {
  985. cs.ProposalBlock = nil
  986. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartsHeader)
  987. }
  988. cs.eventBus.PublishEventUnlock(cs.RoundStateEvent())
  989. cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{})
  990. }
  991. // Enter: any +2/3 precommits for next round.
  992. func (cs *ConsensusState) enterPrecommitWait(height int64, round int) {
  993. logger := cs.Logger.With("height", height, "round", round)
  994. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrecommitWait <= cs.Step) {
  995. logger.Debug(fmt.Sprintf("enterPrecommitWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  996. return
  997. }
  998. if !cs.Votes.Precommits(round).HasTwoThirdsAny() {
  999. cmn.PanicSanity(fmt.Sprintf("enterPrecommitWait(%v/%v), but Precommits does not have any +2/3 votes", height, round))
  1000. }
  1001. logger.Info(fmt.Sprintf("enterPrecommitWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  1002. defer func() {
  1003. // Done enterPrecommitWait:
  1004. cs.updateRoundStep(round, cstypes.RoundStepPrecommitWait)
  1005. cs.newStep()
  1006. }()
  1007. // Wait for some more precommits; enterNewRound
  1008. cs.scheduleTimeout(cs.config.Precommit(round), height, round, cstypes.RoundStepPrecommitWait)
  1009. }
  1010. // Enter: +2/3 precommits for block
  1011. func (cs *ConsensusState) enterCommit(height int64, commitRound int) {
  1012. logger := cs.Logger.With("height", height, "commitRound", commitRound)
  1013. if cs.Height != height || cstypes.RoundStepCommit <= cs.Step {
  1014. logger.Debug(fmt.Sprintf("enterCommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step))
  1015. return
  1016. }
  1017. logger.Info(fmt.Sprintf("enterCommit(%v/%v). Current: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step))
  1018. defer func() {
  1019. // Done enterCommit:
  1020. // keep cs.Round the same, commitRound points to the right Precommits set.
  1021. cs.updateRoundStep(cs.Round, cstypes.RoundStepCommit)
  1022. cs.CommitRound = commitRound
  1023. cs.CommitTime = time.Now()
  1024. cs.newStep()
  1025. // Maybe finalize immediately.
  1026. cs.tryFinalizeCommit(height)
  1027. }()
  1028. blockID, ok := cs.Votes.Precommits(commitRound).TwoThirdsMajority()
  1029. if !ok {
  1030. cmn.PanicSanity("RunActionCommit() expects +2/3 precommits")
  1031. }
  1032. // The Locked* fields no longer matter.
  1033. // Move them over to ProposalBlock if they match the commit hash,
  1034. // otherwise they'll be cleared in updateToState.
  1035. if cs.LockedBlock.HashesTo(blockID.Hash) {
  1036. logger.Info("Commit is for locked block. Set ProposalBlock=LockedBlock", "blockHash", blockID.Hash)
  1037. cs.ProposalBlock = cs.LockedBlock
  1038. cs.ProposalBlockParts = cs.LockedBlockParts
  1039. }
  1040. // If we don't have the block being committed, set up to get it.
  1041. if !cs.ProposalBlock.HashesTo(blockID.Hash) {
  1042. if !cs.ProposalBlockParts.HasHeader(blockID.PartsHeader) {
  1043. logger.Info("Commit is for a block we don't know about. Set ProposalBlock=nil", "proposal", cs.ProposalBlock.Hash(), "commit", blockID.Hash)
  1044. // We're getting the wrong block.
  1045. // Set up ProposalBlockParts and keep waiting.
  1046. cs.ProposalBlock = nil
  1047. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartsHeader)
  1048. } else {
  1049. // We just need to keep waiting.
  1050. }
  1051. }
  1052. }
  1053. // If we have the block AND +2/3 commits for it, finalize.
  1054. func (cs *ConsensusState) tryFinalizeCommit(height int64) {
  1055. logger := cs.Logger.With("height", height)
  1056. if cs.Height != height {
  1057. cmn.PanicSanity(fmt.Sprintf("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height))
  1058. }
  1059. blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  1060. if !ok || len(blockID.Hash) == 0 {
  1061. logger.Error("Attempt to finalize failed. There was no +2/3 majority, or +2/3 was for <nil>.")
  1062. return
  1063. }
  1064. if !cs.ProposalBlock.HashesTo(blockID.Hash) {
  1065. // TODO: this happens every time if we're not a validator (ugly logs)
  1066. // TODO: ^^ wait, why does it matter that we're a validator?
  1067. logger.Info("Attempt to finalize failed. We don't have the commit block.", "proposal-block", cs.ProposalBlock.Hash(), "commit-block", blockID.Hash)
  1068. return
  1069. }
  1070. // go
  1071. cs.finalizeCommit(height)
  1072. }
  1073. // Increment height and goto cstypes.RoundStepNewHeight
  1074. func (cs *ConsensusState) finalizeCommit(height int64) {
  1075. if cs.Height != height || cs.Step != cstypes.RoundStepCommit {
  1076. cs.Logger.Debug(fmt.Sprintf("finalizeCommit(%v): Invalid args. Current step: %v/%v/%v", height, cs.Height, cs.Round, cs.Step))
  1077. return
  1078. }
  1079. blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  1080. block, blockParts := cs.ProposalBlock, cs.ProposalBlockParts
  1081. if !ok {
  1082. cmn.PanicSanity(fmt.Sprintf("Cannot finalizeCommit, commit does not have two thirds majority"))
  1083. }
  1084. if !blockParts.HasHeader(blockID.PartsHeader) {
  1085. cmn.PanicSanity(fmt.Sprintf("Expected ProposalBlockParts header to be commit header"))
  1086. }
  1087. if !block.HashesTo(blockID.Hash) {
  1088. cmn.PanicSanity(fmt.Sprintf("Cannot finalizeCommit, ProposalBlock does not hash to commit hash"))
  1089. }
  1090. if err := cs.blockExec.ValidateBlock(cs.state, block); err != nil {
  1091. cmn.PanicConsensus(fmt.Sprintf("+2/3 committed an invalid block: %v", err))
  1092. }
  1093. cs.Logger.Info(fmt.Sprintf("Finalizing commit of block with %d txs", block.NumTxs),
  1094. "height", block.Height, "hash", block.Hash(), "root", block.AppHash)
  1095. cs.Logger.Info(fmt.Sprintf("%v", block))
  1096. fail.Fail() // XXX
  1097. // Save to blockStore.
  1098. if cs.blockStore.Height() < block.Height {
  1099. // NOTE: the seenCommit is local justification to commit this block,
  1100. // but may differ from the LastCommit included in the next block
  1101. precommits := cs.Votes.Precommits(cs.CommitRound)
  1102. seenCommit := precommits.MakeCommit()
  1103. cs.blockStore.SaveBlock(block, blockParts, seenCommit)
  1104. } else {
  1105. // Happens during replay if we already saved the block but didn't commit
  1106. cs.Logger.Info("Calling finalizeCommit on already stored block", "height", block.Height)
  1107. }
  1108. fail.Fail() // XXX
  1109. // Write EndHeightMessage{} for this height, implying that the blockstore
  1110. // has saved the block.
  1111. //
  1112. // If we crash before writing this EndHeightMessage{}, we will recover by
  1113. // running ApplyBlock during the ABCI handshake when we restart. If we
  1114. // didn't save the block to the blockstore before writing
  1115. // EndHeightMessage{}, we'd have to change WAL replay -- currently it
  1116. // complains about replaying for heights where an #ENDHEIGHT entry already
  1117. // exists.
  1118. //
  1119. // Either way, the ConsensusState should not be resumed until we
  1120. // successfully call ApplyBlock (ie. later here, or in Handshake after
  1121. // restart).
  1122. cs.wal.WriteSync(EndHeightMessage{height}) // NOTE: fsync
  1123. fail.Fail() // XXX
  1124. // Create a copy of the state for staging and an event cache for txs.
  1125. stateCopy := cs.state.Copy()
  1126. // Execute and commit the block, update and save the state, and update the mempool.
  1127. // NOTE The block.AppHash wont reflect these txs until the next block.
  1128. var err error
  1129. stateCopy, err = cs.blockExec.ApplyBlock(stateCopy, types.BlockID{block.Hash(), blockParts.Header()}, block)
  1130. if err != nil {
  1131. cs.Logger.Error("Error on ApplyBlock. Did the application crash? Please restart tendermint", "err", err)
  1132. err := cmn.Kill()
  1133. if err != nil {
  1134. cs.Logger.Error("Failed to kill this process - please do so manually", "err", err)
  1135. }
  1136. return
  1137. }
  1138. fail.Fail() // XXX
  1139. // must be called before we update state
  1140. cs.recordMetrics(height, block)
  1141. // NewHeightStep!
  1142. cs.updateToState(stateCopy)
  1143. fail.Fail() // XXX
  1144. // cs.StartTime is already set.
  1145. // Schedule Round0 to start soon.
  1146. cs.scheduleRound0(&cs.RoundState)
  1147. // By here,
  1148. // * cs.Height has been increment to height+1
  1149. // * cs.Step is now cstypes.RoundStepNewHeight
  1150. // * cs.StartTime is set to when we will start round0.
  1151. }
  1152. func (cs *ConsensusState) recordMetrics(height int64, block *types.Block) {
  1153. cs.metrics.Validators.Set(float64(cs.Validators.Size()))
  1154. cs.metrics.ValidatorsPower.Set(float64(cs.Validators.TotalVotingPower()))
  1155. missingValidators := 0
  1156. missingValidatorsPower := int64(0)
  1157. for i, val := range cs.Validators.Validators {
  1158. var vote *types.Vote
  1159. if i < len(block.LastCommit.Precommits) {
  1160. vote = block.LastCommit.Precommits[i]
  1161. }
  1162. if vote == nil {
  1163. missingValidators++
  1164. missingValidatorsPower += val.VotingPower
  1165. }
  1166. }
  1167. cs.metrics.MissingValidators.Set(float64(missingValidators))
  1168. cs.metrics.MissingValidatorsPower.Set(float64(missingValidatorsPower))
  1169. cs.metrics.ByzantineValidators.Set(float64(len(block.Evidence.Evidence)))
  1170. byzantineValidatorsPower := int64(0)
  1171. for _, ev := range block.Evidence.Evidence {
  1172. if _, val := cs.Validators.GetByAddress(ev.Address()); val != nil {
  1173. byzantineValidatorsPower += val.VotingPower
  1174. }
  1175. }
  1176. cs.metrics.ByzantineValidatorsPower.Set(float64(byzantineValidatorsPower))
  1177. if height > 1 {
  1178. lastBlockMeta := cs.blockStore.LoadBlockMeta(height - 1)
  1179. cs.metrics.BlockIntervalSeconds.Observe(
  1180. block.Time.Sub(lastBlockMeta.Header.Time).Seconds(),
  1181. )
  1182. }
  1183. cs.metrics.NumTxs.Set(float64(block.NumTxs))
  1184. cs.metrics.BlockSizeBytes.Set(float64(block.Size()))
  1185. cs.metrics.TotalTxs.Set(float64(block.TotalTxs))
  1186. }
  1187. //-----------------------------------------------------------------------------
  1188. func (cs *ConsensusState) defaultSetProposal(proposal *types.Proposal) error {
  1189. // Already have one
  1190. // TODO: possibly catch double proposals
  1191. if cs.Proposal != nil {
  1192. return nil
  1193. }
  1194. // Does not apply
  1195. if proposal.Height != cs.Height || proposal.Round != cs.Round {
  1196. return nil
  1197. }
  1198. // We don't care about the proposal if we're already in cstypes.RoundStepCommit.
  1199. if cstypes.RoundStepCommit <= cs.Step {
  1200. return nil
  1201. }
  1202. // Verify POLRound, which must be -1 or between 0 and proposal.Round exclusive.
  1203. if proposal.POLRound != -1 &&
  1204. (proposal.POLRound < 0 || proposal.Round <= proposal.POLRound) {
  1205. return ErrInvalidProposalPOLRound
  1206. }
  1207. // Verify signature
  1208. if !cs.Validators.GetProposer().PubKey.VerifyBytes(proposal.SignBytes(cs.state.ChainID), proposal.Signature) {
  1209. return ErrInvalidProposalSignature
  1210. }
  1211. cs.Proposal = proposal
  1212. cs.ProposalBlockParts = types.NewPartSetFromHeader(proposal.BlockPartsHeader)
  1213. cs.Logger.Info("Received proposal", "proposal", proposal)
  1214. return nil
  1215. }
  1216. // NOTE: block is not necessarily valid.
  1217. // Asynchronously triggers either enterPrevote (before we timeout of propose) or tryFinalizeCommit, once we have the full block.
  1218. func (cs *ConsensusState) addProposalBlockPart(msg *BlockPartMessage, peerID p2p.ID) (added bool, err error) {
  1219. height, round, part := msg.Height, msg.Round, msg.Part
  1220. // Blocks might be reused, so round mismatch is OK
  1221. if cs.Height != height {
  1222. cs.Logger.Debug("Received block part from wrong height", "height", height, "round", round)
  1223. return false, nil
  1224. }
  1225. // We're not expecting a block part.
  1226. if cs.ProposalBlockParts == nil {
  1227. // NOTE: this can happen when we've gone to a higher round and
  1228. // then receive parts from the previous round - not necessarily a bad peer.
  1229. cs.Logger.Info("Received a block part when we're not expecting any",
  1230. "height", height, "round", round, "index", part.Index, "peer", peerID)
  1231. return false, nil
  1232. }
  1233. added, err = cs.ProposalBlockParts.AddPart(part)
  1234. if err != nil {
  1235. return added, err
  1236. }
  1237. if added && cs.ProposalBlockParts.IsComplete() {
  1238. // Added and completed!
  1239. _, err = cdc.UnmarshalBinaryReader(cs.ProposalBlockParts.GetReader(), &cs.ProposalBlock, int64(cs.state.ConsensusParams.BlockSize.MaxBytes))
  1240. if err != nil {
  1241. return true, err
  1242. }
  1243. // NOTE: it's possible to receive complete proposal blocks for future rounds without having the proposal
  1244. cs.Logger.Info("Received complete proposal block", "height", cs.ProposalBlock.Height, "hash", cs.ProposalBlock.Hash())
  1245. // Update Valid* if we can.
  1246. prevotes := cs.Votes.Prevotes(cs.Round)
  1247. blockID, hasTwoThirds := prevotes.TwoThirdsMajority()
  1248. if hasTwoThirds && !blockID.IsZero() && (cs.ValidRound < cs.Round) {
  1249. if cs.ProposalBlock.HashesTo(blockID.Hash) {
  1250. cs.Logger.Info("Updating valid block to new proposal block",
  1251. "valid-round", cs.Round, "valid-block-hash", cs.ProposalBlock.Hash())
  1252. cs.ValidRound = cs.Round
  1253. cs.ValidBlock = cs.ProposalBlock
  1254. cs.ValidBlockParts = cs.ProposalBlockParts
  1255. }
  1256. // TODO: In case there is +2/3 majority in Prevotes set for some
  1257. // block and cs.ProposalBlock contains different block, either
  1258. // proposer is faulty or voting power of faulty processes is more
  1259. // than 1/3. We should trigger in the future accountability
  1260. // procedure at this point.
  1261. }
  1262. if cs.Step <= cstypes.RoundStepPropose && cs.isProposalComplete() {
  1263. // Move onto the next step
  1264. cs.enterPrevote(height, cs.Round)
  1265. } else if cs.Step == cstypes.RoundStepCommit {
  1266. // If we're waiting on the proposal block...
  1267. cs.tryFinalizeCommit(height)
  1268. }
  1269. return true, nil
  1270. }
  1271. return added, nil
  1272. }
  1273. // Attempt to add the vote. if its a duplicate signature, dupeout the validator
  1274. func (cs *ConsensusState) tryAddVote(vote *types.Vote, peerID p2p.ID) error {
  1275. _, err := cs.addVote(vote, peerID)
  1276. if err != nil {
  1277. // If the vote height is off, we'll just ignore it,
  1278. // But if it's a conflicting sig, add it to the cs.evpool.
  1279. // If it's otherwise invalid, punish peer.
  1280. if err == ErrVoteHeightMismatch {
  1281. return err
  1282. } else if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok {
  1283. if bytes.Equal(vote.ValidatorAddress, cs.privValidator.GetAddress()) {
  1284. cs.Logger.Error("Found conflicting vote from ourselves. Did you unsafe_reset a validator?", "height", vote.Height, "round", vote.Round, "type", vote.Type)
  1285. return err
  1286. }
  1287. cs.evpool.AddEvidence(voteErr.DuplicateVoteEvidence)
  1288. return err
  1289. } else {
  1290. // Probably an invalid signature / Bad peer.
  1291. // Seems this can also err sometimes with "Unexpected step" - perhaps not from a bad peer ?
  1292. cs.Logger.Error("Error attempting to add vote", "err", err)
  1293. return ErrAddingVote
  1294. }
  1295. }
  1296. return nil
  1297. }
  1298. //-----------------------------------------------------------------------------
  1299. func (cs *ConsensusState) addVote(vote *types.Vote, peerID p2p.ID) (added bool, err error) {
  1300. cs.Logger.Debug("addVote", "voteHeight", vote.Height, "voteType", vote.Type, "valIndex", vote.ValidatorIndex, "csHeight", cs.Height)
  1301. // A precommit for the previous height?
  1302. // These come in while we wait timeoutCommit
  1303. if vote.Height+1 == cs.Height {
  1304. if !(cs.Step == cstypes.RoundStepNewHeight && vote.Type == types.VoteTypePrecommit) {
  1305. // TODO: give the reason ..
  1306. // fmt.Errorf("tryAddVote: Wrong height, not a LastCommit straggler commit.")
  1307. return added, ErrVoteHeightMismatch
  1308. }
  1309. added, err = cs.LastCommit.AddVote(vote)
  1310. if !added {
  1311. return added, err
  1312. }
  1313. cs.Logger.Info(fmt.Sprintf("Added to lastPrecommits: %v", cs.LastCommit.StringShort()))
  1314. cs.eventBus.PublishEventVote(types.EventDataVote{vote})
  1315. cs.evsw.FireEvent(types.EventVote, vote)
  1316. // if we can skip timeoutCommit and have all the votes now,
  1317. if cs.config.SkipTimeoutCommit && cs.LastCommit.HasAll() {
  1318. // go straight to new round (skip timeout commit)
  1319. // cs.scheduleTimeout(time.Duration(0), cs.Height, 0, cstypes.RoundStepNewHeight)
  1320. cs.enterNewRound(cs.Height, 0)
  1321. }
  1322. return
  1323. }
  1324. // Height mismatch is ignored.
  1325. // Not necessarily a bad peer, but not favourable behaviour.
  1326. if vote.Height != cs.Height {
  1327. err = ErrVoteHeightMismatch
  1328. cs.Logger.Info("Vote ignored and not added", "voteHeight", vote.Height, "csHeight", cs.Height, "err", err)
  1329. return
  1330. }
  1331. height := cs.Height
  1332. added, err = cs.Votes.AddVote(vote, peerID)
  1333. if !added {
  1334. // Either duplicate, or error upon cs.Votes.AddByIndex()
  1335. return
  1336. }
  1337. cs.eventBus.PublishEventVote(types.EventDataVote{vote})
  1338. cs.evsw.FireEvent(types.EventVote, vote)
  1339. switch vote.Type {
  1340. case types.VoteTypePrevote:
  1341. prevotes := cs.Votes.Prevotes(vote.Round)
  1342. cs.Logger.Info("Added to prevote", "vote", vote, "prevotes", prevotes.StringShort())
  1343. // If +2/3 prevotes for a block or nil for *any* round:
  1344. if blockID, ok := prevotes.TwoThirdsMajority(); ok {
  1345. // There was a polka!
  1346. // If we're locked but this is a recent polka, unlock.
  1347. // If it matches our ProposalBlock, update the ValidBlock
  1348. // Unlock if `cs.LockedRound < vote.Round <= cs.Round`
  1349. // NOTE: If vote.Round > cs.Round, we'll deal with it when we get to vote.Round
  1350. if (cs.LockedBlock != nil) &&
  1351. (cs.LockedRound < vote.Round) &&
  1352. (vote.Round <= cs.Round) &&
  1353. !cs.LockedBlock.HashesTo(blockID.Hash) {
  1354. cs.Logger.Info("Unlocking because of POL.", "lockedRound", cs.LockedRound, "POLRound", vote.Round)
  1355. cs.LockedRound = 0
  1356. cs.LockedBlock = nil
  1357. cs.LockedBlockParts = nil
  1358. cs.eventBus.PublishEventUnlock(cs.RoundStateEvent())
  1359. }
  1360. // Update Valid* if we can.
  1361. // NOTE: our proposal block may be nil or not what received a polka..
  1362. // TODO: we may want to still update the ValidBlock and obtain it via gossipping
  1363. if !blockID.IsZero() &&
  1364. (cs.ValidRound < vote.Round) &&
  1365. (vote.Round <= cs.Round) &&
  1366. cs.ProposalBlock.HashesTo(blockID.Hash) {
  1367. cs.Logger.Info("Updating ValidBlock because of POL.", "validRound", cs.ValidRound, "POLRound", vote.Round)
  1368. cs.ValidRound = vote.Round
  1369. cs.ValidBlock = cs.ProposalBlock
  1370. cs.ValidBlockParts = cs.ProposalBlockParts
  1371. }
  1372. }
  1373. // If +2/3 prevotes for *anything* for this or future round:
  1374. if cs.Round <= vote.Round && prevotes.HasTwoThirdsAny() {
  1375. // Round-skip over to PrevoteWait or goto Precommit.
  1376. cs.enterNewRound(height, vote.Round) // if the vote is ahead of us
  1377. if prevotes.HasTwoThirdsMajority() {
  1378. cs.enterPrecommit(height, vote.Round)
  1379. } else {
  1380. cs.enterPrevote(height, vote.Round) // if the vote is ahead of us
  1381. cs.enterPrevoteWait(height, vote.Round)
  1382. }
  1383. } else if cs.Proposal != nil && 0 <= cs.Proposal.POLRound && cs.Proposal.POLRound == vote.Round {
  1384. // If the proposal is now complete, enter prevote of cs.Round.
  1385. if cs.isProposalComplete() {
  1386. cs.enterPrevote(height, cs.Round)
  1387. }
  1388. }
  1389. case types.VoteTypePrecommit:
  1390. precommits := cs.Votes.Precommits(vote.Round)
  1391. cs.Logger.Info("Added to precommit", "vote", vote, "precommits", precommits.StringShort())
  1392. blockID, ok := precommits.TwoThirdsMajority()
  1393. if ok {
  1394. if len(blockID.Hash) == 0 {
  1395. cs.enterNewRound(height, vote.Round+1)
  1396. } else {
  1397. cs.enterNewRound(height, vote.Round)
  1398. cs.enterPrecommit(height, vote.Round)
  1399. cs.enterCommit(height, vote.Round)
  1400. if cs.config.SkipTimeoutCommit && precommits.HasAll() {
  1401. // if we have all the votes now,
  1402. // go straight to new round (skip timeout commit)
  1403. // cs.scheduleTimeout(time.Duration(0), cs.Height, 0, cstypes.RoundStepNewHeight)
  1404. cs.enterNewRound(cs.Height, 0)
  1405. }
  1406. }
  1407. } else if cs.Round <= vote.Round && precommits.HasTwoThirdsAny() {
  1408. cs.enterNewRound(height, vote.Round)
  1409. cs.enterPrecommit(height, vote.Round)
  1410. cs.enterPrecommitWait(height, vote.Round)
  1411. }
  1412. default:
  1413. panic(fmt.Sprintf("Unexpected vote type %X", vote.Type)) // go-wire should prevent this.
  1414. }
  1415. return
  1416. }
  1417. func (cs *ConsensusState) signVote(type_ byte, hash []byte, header types.PartSetHeader) (*types.Vote, error) {
  1418. addr := cs.privValidator.GetAddress()
  1419. valIndex, _ := cs.Validators.GetByAddress(addr)
  1420. vote := &types.Vote{
  1421. ValidatorAddress: addr,
  1422. ValidatorIndex: valIndex,
  1423. Height: cs.Height,
  1424. Round: cs.Round,
  1425. Timestamp: time.Now().UTC(),
  1426. Type: type_,
  1427. BlockID: types.BlockID{hash, header},
  1428. }
  1429. err := cs.privValidator.SignVote(cs.state.ChainID, vote)
  1430. return vote, err
  1431. }
  1432. // sign the vote and publish on internalMsgQueue
  1433. func (cs *ConsensusState) signAddVote(type_ byte, hash []byte, header types.PartSetHeader) *types.Vote {
  1434. // if we don't have a key or we're not in the validator set, do nothing
  1435. if cs.privValidator == nil || !cs.Validators.HasAddress(cs.privValidator.GetAddress()) {
  1436. return nil
  1437. }
  1438. vote, err := cs.signVote(type_, hash, header)
  1439. if err == nil {
  1440. cs.sendInternalMessage(msgInfo{&VoteMessage{vote}, ""})
  1441. cs.Logger.Info("Signed and pushed vote", "height", cs.Height, "round", cs.Round, "vote", vote, "err", err)
  1442. return vote
  1443. }
  1444. //if !cs.replayMode {
  1445. cs.Logger.Error("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "err", err)
  1446. //}
  1447. return nil
  1448. }
  1449. //---------------------------------------------------------
  1450. func CompareHRS(h1 int64, r1 int, s1 cstypes.RoundStepType, h2 int64, r2 int, s2 cstypes.RoundStepType) int {
  1451. if h1 < h2 {
  1452. return -1
  1453. } else if h1 > h2 {
  1454. return 1
  1455. }
  1456. if r1 < r2 {
  1457. return -1
  1458. } else if r1 > r2 {
  1459. return 1
  1460. }
  1461. if s1 < s2 {
  1462. return -1
  1463. } else if s1 > s2 {
  1464. return 1
  1465. }
  1466. return 0
  1467. }