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.

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