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.

1527 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
9 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
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 ```
6 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 ```
6 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
7 years ago
9 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
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
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
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
7 years ago
10 years ago
7 years ago
10 years ago
7 years ago
9 years ago
9 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
7 years ago
7 years ago
10 years ago
7 years ago
10 years ago
10 years ago
10 years ago
7 years ago
9 years ago
9 years ago
7 years ago
7 years ago
10 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
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
7 years ago
7 years ago
7 years ago
7 years ago
10 years ago
7 years ago
10 years ago
10 years ago
7 years ago
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
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
10 years ago
10 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
10 years ago
10 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
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
9 years ago
7 years ago
7 years ago
9 years ago
7 years ago
10 years ago
7 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
7 years ago
9 years ago
9 years ago
7 years ago
10 years ago
10 years ago
7 years ago
7 years ago
8 years ago
7 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
6 years ago
9 years ago
7 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)
  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. // check for a polka
  859. blockID, ok := cs.Votes.Prevotes(round).TwoThirdsMajority()
  860. // If we don't have a polka, we must precommit nil
  861. if !ok {
  862. if cs.LockedBlock != nil {
  863. cs.Logger.Info("enterPrecommit: No +2/3 prevotes during enterPrecommit while we're locked. Precommitting nil")
  864. } else {
  865. cs.Logger.Info("enterPrecommit: No +2/3 prevotes during enterPrecommit. Precommitting nil.")
  866. }
  867. cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{})
  868. return
  869. }
  870. // At this point +2/3 prevoted for a particular block or nil
  871. cs.eventBus.PublishEventPolka(cs.RoundStateEvent())
  872. // the latest POLRound should be this round
  873. polRound, _ := cs.Votes.POLInfo()
  874. if polRound < round {
  875. cmn.PanicSanity(cmn.Fmt("This POLRound should be %v but got %", round, polRound))
  876. }
  877. // +2/3 prevoted nil. Unlock and precommit nil.
  878. if len(blockID.Hash) == 0 {
  879. if cs.LockedBlock == nil {
  880. cs.Logger.Info("enterPrecommit: +2/3 prevoted for nil.")
  881. } else {
  882. cs.Logger.Info("enterPrecommit: +2/3 prevoted for nil. Unlocking")
  883. cs.LockedRound = 0
  884. cs.LockedBlock = nil
  885. cs.LockedBlockParts = nil
  886. cs.eventBus.PublishEventUnlock(cs.RoundStateEvent())
  887. }
  888. cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{})
  889. return
  890. }
  891. // At this point, +2/3 prevoted for a particular block.
  892. // If we're already locked on that block, precommit it, and update the LockedRound
  893. if cs.LockedBlock.HashesTo(blockID.Hash) {
  894. cs.Logger.Info("enterPrecommit: +2/3 prevoted locked block. Relocking")
  895. cs.LockedRound = round
  896. cs.eventBus.PublishEventRelock(cs.RoundStateEvent())
  897. cs.signAddVote(types.VoteTypePrecommit, blockID.Hash, blockID.PartsHeader)
  898. return
  899. }
  900. // If +2/3 prevoted for proposal block, stage and precommit it
  901. if cs.ProposalBlock.HashesTo(blockID.Hash) {
  902. cs.Logger.Info("enterPrecommit: +2/3 prevoted proposal block. Locking", "hash", blockID.Hash)
  903. // Validate the block.
  904. if err := cs.blockExec.ValidateBlock(cs.state, cs.ProposalBlock); err != nil {
  905. cmn.PanicConsensus(cmn.Fmt("enterPrecommit: +2/3 prevoted for an invalid block: %v", err))
  906. }
  907. cs.LockedRound = round
  908. cs.LockedBlock = cs.ProposalBlock
  909. cs.LockedBlockParts = cs.ProposalBlockParts
  910. cs.eventBus.PublishEventLock(cs.RoundStateEvent())
  911. cs.signAddVote(types.VoteTypePrecommit, blockID.Hash, blockID.PartsHeader)
  912. return
  913. }
  914. // There was a polka in this round for a block we don't have.
  915. // Fetch that block, unlock, and precommit nil.
  916. // The +2/3 prevotes for this round is the POL for our unlock.
  917. // TODO: In the future save the POL prevotes for justification.
  918. cs.LockedRound = 0
  919. cs.LockedBlock = nil
  920. cs.LockedBlockParts = nil
  921. if !cs.ProposalBlockParts.HasHeader(blockID.PartsHeader) {
  922. cs.ProposalBlock = nil
  923. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartsHeader)
  924. }
  925. cs.eventBus.PublishEventUnlock(cs.RoundStateEvent())
  926. cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{})
  927. }
  928. // Enter: any +2/3 precommits for next round.
  929. func (cs *ConsensusState) enterPrecommitWait(height int64, round int) {
  930. if cs.Height != height || round < cs.Round || (cs.Round == round && cstypes.RoundStepPrecommitWait <= cs.Step) {
  931. cs.Logger.Debug(cmn.Fmt("enterPrecommitWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  932. return
  933. }
  934. if !cs.Votes.Precommits(round).HasTwoThirdsAny() {
  935. cmn.PanicSanity(cmn.Fmt("enterPrecommitWait(%v/%v), but Precommits does not have any +2/3 votes", height, round))
  936. }
  937. cs.Logger.Info(cmn.Fmt("enterPrecommitWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step))
  938. defer func() {
  939. // Done enterPrecommitWait:
  940. cs.updateRoundStep(round, cstypes.RoundStepPrecommitWait)
  941. cs.newStep()
  942. }()
  943. // Wait for some more precommits; enterNewRound
  944. cs.scheduleTimeout(cs.config.Precommit(round), height, round, cstypes.RoundStepPrecommitWait)
  945. }
  946. // Enter: +2/3 precommits for block
  947. func (cs *ConsensusState) enterCommit(height int64, commitRound int) {
  948. if cs.Height != height || cstypes.RoundStepCommit <= cs.Step {
  949. cs.Logger.Debug(cmn.Fmt("enterCommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step))
  950. return
  951. }
  952. cs.Logger.Info(cmn.Fmt("enterCommit(%v/%v). Current: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step))
  953. defer func() {
  954. // Done enterCommit:
  955. // keep cs.Round the same, commitRound points to the right Precommits set.
  956. cs.updateRoundStep(cs.Round, cstypes.RoundStepCommit)
  957. cs.CommitRound = commitRound
  958. cs.CommitTime = time.Now()
  959. cs.newStep()
  960. // Maybe finalize immediately.
  961. cs.tryFinalizeCommit(height)
  962. }()
  963. blockID, ok := cs.Votes.Precommits(commitRound).TwoThirdsMajority()
  964. if !ok {
  965. cmn.PanicSanity("RunActionCommit() expects +2/3 precommits")
  966. }
  967. // The Locked* fields no longer matter.
  968. // Move them over to ProposalBlock if they match the commit hash,
  969. // otherwise they'll be cleared in updateToState.
  970. if cs.LockedBlock.HashesTo(blockID.Hash) {
  971. cs.ProposalBlock = cs.LockedBlock
  972. cs.ProposalBlockParts = cs.LockedBlockParts
  973. }
  974. // If we don't have the block being committed, set up to get it.
  975. if !cs.ProposalBlock.HashesTo(blockID.Hash) {
  976. if !cs.ProposalBlockParts.HasHeader(blockID.PartsHeader) {
  977. // We're getting the wrong block.
  978. // Set up ProposalBlockParts and keep waiting.
  979. cs.ProposalBlock = nil
  980. cs.ProposalBlockParts = types.NewPartSetFromHeader(blockID.PartsHeader)
  981. } else {
  982. // We just need to keep waiting.
  983. }
  984. }
  985. }
  986. // If we have the block AND +2/3 commits for it, finalize.
  987. func (cs *ConsensusState) tryFinalizeCommit(height int64) {
  988. if cs.Height != height {
  989. cmn.PanicSanity(cmn.Fmt("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height))
  990. }
  991. blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  992. if !ok || len(blockID.Hash) == 0 {
  993. cs.Logger.Error("Attempt to finalize failed. There was no +2/3 majority, or +2/3 was for <nil>.", "height", height)
  994. return
  995. }
  996. if !cs.ProposalBlock.HashesTo(blockID.Hash) {
  997. // TODO: this happens every time if we're not a validator (ugly logs)
  998. // TODO: ^^ wait, why does it matter that we're a validator?
  999. 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)
  1000. return
  1001. }
  1002. // go
  1003. cs.finalizeCommit(height)
  1004. }
  1005. // Increment height and goto cstypes.RoundStepNewHeight
  1006. func (cs *ConsensusState) finalizeCommit(height int64) {
  1007. if cs.Height != height || cs.Step != cstypes.RoundStepCommit {
  1008. cs.Logger.Debug(cmn.Fmt("finalizeCommit(%v): Invalid args. Current step: %v/%v/%v", height, cs.Height, cs.Round, cs.Step))
  1009. return
  1010. }
  1011. blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority()
  1012. block, blockParts := cs.ProposalBlock, cs.ProposalBlockParts
  1013. if !ok {
  1014. cmn.PanicSanity(cmn.Fmt("Cannot finalizeCommit, commit does not have two thirds majority"))
  1015. }
  1016. if !blockParts.HasHeader(blockID.PartsHeader) {
  1017. cmn.PanicSanity(cmn.Fmt("Expected ProposalBlockParts header to be commit header"))
  1018. }
  1019. if !block.HashesTo(blockID.Hash) {
  1020. cmn.PanicSanity(cmn.Fmt("Cannot finalizeCommit, ProposalBlock does not hash to commit hash"))
  1021. }
  1022. if err := cs.blockExec.ValidateBlock(cs.state, block); err != nil {
  1023. cmn.PanicConsensus(cmn.Fmt("+2/3 committed an invalid block: %v", err))
  1024. }
  1025. cs.Logger.Info(cmn.Fmt("Finalizing commit of block with %d txs", block.NumTxs),
  1026. "height", block.Height, "hash", block.Hash(), "root", block.AppHash)
  1027. cs.Logger.Info(cmn.Fmt("%v", block))
  1028. fail.Fail() // XXX
  1029. // Save to blockStore.
  1030. if cs.blockStore.Height() < block.Height {
  1031. // NOTE: the seenCommit is local justification to commit this block,
  1032. // but may differ from the LastCommit included in the next block
  1033. precommits := cs.Votes.Precommits(cs.CommitRound)
  1034. seenCommit := precommits.MakeCommit()
  1035. cs.blockStore.SaveBlock(block, blockParts, seenCommit)
  1036. } else {
  1037. // Happens during replay if we already saved the block but didn't commit
  1038. cs.Logger.Info("Calling finalizeCommit on already stored block", "height", block.Height)
  1039. }
  1040. fail.Fail() // XXX
  1041. // Finish writing to the WAL for this height.
  1042. // NOTE: If we fail before writing this, we'll never write it,
  1043. // and just recover by running ApplyBlock in the Handshake.
  1044. // If we moved it before persisting the block, we'd have to allow
  1045. // WAL replay for blocks with an #ENDHEIGHT
  1046. // As is, ConsensusState should not be started again
  1047. // until we successfully call ApplyBlock (ie. here or in Handshake after restart)
  1048. cs.wal.Save(EndHeightMessage{height})
  1049. fail.Fail() // XXX
  1050. // Create a copy of the state for staging
  1051. // and an event cache for txs
  1052. stateCopy := cs.state.Copy()
  1053. // Execute and commit the block, update and save the state, and update the mempool.
  1054. // NOTE: the block.AppHash wont reflect these txs until the next block
  1055. var err error
  1056. stateCopy, err = cs.blockExec.ApplyBlock(stateCopy, types.BlockID{block.Hash(), blockParts.Header()}, block)
  1057. if err != nil {
  1058. cs.Logger.Error("Error on ApplyBlock. Did the application crash? Please restart tendermint", "err", err)
  1059. err := cmn.Kill()
  1060. if err != nil {
  1061. cs.Logger.Error("Failed to kill this process - please do so manually", "err", err)
  1062. }
  1063. return
  1064. }
  1065. fail.Fail() // XXX
  1066. // NewHeightStep!
  1067. cs.updateToState(stateCopy)
  1068. fail.Fail() // XXX
  1069. // cs.StartTime is already set.
  1070. // Schedule Round0 to start soon.
  1071. cs.scheduleRound0(&cs.RoundState)
  1072. // By here,
  1073. // * cs.Height has been increment to height+1
  1074. // * cs.Step is now cstypes.RoundStepNewHeight
  1075. // * cs.StartTime is set to when we will start round0.
  1076. }
  1077. //-----------------------------------------------------------------------------
  1078. func (cs *ConsensusState) defaultSetProposal(proposal *types.Proposal) error {
  1079. // Already have one
  1080. // TODO: possibly catch double proposals
  1081. if cs.Proposal != nil {
  1082. return nil
  1083. }
  1084. // Does not apply
  1085. if proposal.Height != cs.Height || proposal.Round != cs.Round {
  1086. return nil
  1087. }
  1088. // We don't care about the proposal if we're already in cstypes.RoundStepCommit.
  1089. if cstypes.RoundStepCommit <= cs.Step {
  1090. return nil
  1091. }
  1092. // Verify POLRound, which must be -1 or between 0 and proposal.Round exclusive.
  1093. if proposal.POLRound != -1 &&
  1094. (proposal.POLRound < 0 || proposal.Round <= proposal.POLRound) {
  1095. return ErrInvalidProposalPOLRound
  1096. }
  1097. // Verify signature
  1098. if !cs.Validators.GetProposer().PubKey.VerifyBytes(proposal.SignBytes(cs.state.ChainID), proposal.Signature) {
  1099. return ErrInvalidProposalSignature
  1100. }
  1101. cs.Proposal = proposal
  1102. cs.ProposalBlockParts = types.NewPartSetFromHeader(proposal.BlockPartsHeader)
  1103. return nil
  1104. }
  1105. // NOTE: block is not necessarily valid.
  1106. // Asynchronously triggers either enterPrevote (before we timeout of propose) or tryFinalizeCommit, once we have the full block.
  1107. func (cs *ConsensusState) addProposalBlockPart(height int64, part *types.Part, verify bool) (added bool, err error) {
  1108. // Blocks might be reused, so round mismatch is OK
  1109. if cs.Height != height {
  1110. return false, nil
  1111. }
  1112. // We're not expecting a block part.
  1113. if cs.ProposalBlockParts == nil {
  1114. return false, nil // TODO: bad peer? Return error?
  1115. }
  1116. added, err = cs.ProposalBlockParts.AddPart(part, verify)
  1117. if err != nil {
  1118. return added, err
  1119. }
  1120. if added && cs.ProposalBlockParts.IsComplete() {
  1121. // Added and completed!
  1122. _, err = cdc.UnmarshalBinaryReader(cs.ProposalBlockParts.GetReader(), &cs.ProposalBlock, int64(cs.state.ConsensusParams.BlockSize.MaxBytes))
  1123. if err != nil {
  1124. return true, err
  1125. }
  1126. // NOTE: it's possible to receive complete proposal blocks for future rounds without having the proposal
  1127. cs.Logger.Info("Received complete proposal block", "height", cs.ProposalBlock.Height, "hash", cs.ProposalBlock.Hash())
  1128. if cs.Step == cstypes.RoundStepPropose && cs.isProposalComplete() {
  1129. // Move onto the next step
  1130. cs.enterPrevote(height, cs.Round)
  1131. } else if cs.Step == cstypes.RoundStepCommit {
  1132. // If we're waiting on the proposal block...
  1133. cs.tryFinalizeCommit(height)
  1134. }
  1135. return true, nil
  1136. }
  1137. return added, nil
  1138. }
  1139. // Attempt to add the vote. if its a duplicate signature, dupeout the validator
  1140. func (cs *ConsensusState) tryAddVote(vote *types.Vote, peerID p2p.ID) error {
  1141. _, err := cs.addVote(vote, peerID)
  1142. if err != nil {
  1143. // If the vote height is off, we'll just ignore it,
  1144. // But if it's a conflicting sig, add it to the cs.evpool.
  1145. // If it's otherwise invalid, punish peer.
  1146. if err == ErrVoteHeightMismatch {
  1147. return err
  1148. } else if voteErr, ok := err.(*types.ErrVoteConflictingVotes); ok {
  1149. if bytes.Equal(vote.ValidatorAddress, cs.privValidator.GetAddress()) {
  1150. cs.Logger.Error("Found conflicting vote from ourselves. Did you unsafe_reset a validator?", "height", vote.Height, "round", vote.Round, "type", vote.Type)
  1151. return err
  1152. }
  1153. cs.evpool.AddEvidence(voteErr.DuplicateVoteEvidence)
  1154. return err
  1155. } else {
  1156. // Probably an invalid signature / Bad peer.
  1157. // Seems this can also err sometimes with "Unexpected step" - perhaps not from a bad peer ?
  1158. cs.Logger.Error("Error attempting to add vote", "err", err)
  1159. return ErrAddingVote
  1160. }
  1161. }
  1162. return nil
  1163. }
  1164. //-----------------------------------------------------------------------------
  1165. func (cs *ConsensusState) addVote(vote *types.Vote, peerID p2p.ID) (added bool, err error) {
  1166. cs.Logger.Debug("addVote", "voteHeight", vote.Height, "voteType", vote.Type, "valIndex", vote.ValidatorIndex, "csHeight", cs.Height)
  1167. // A precommit for the previous height?
  1168. // These come in while we wait timeoutCommit
  1169. if vote.Height+1 == cs.Height {
  1170. if !(cs.Step == cstypes.RoundStepNewHeight && vote.Type == types.VoteTypePrecommit) {
  1171. // TODO: give the reason ..
  1172. // fmt.Errorf("tryAddVote: Wrong height, not a LastCommit straggler commit.")
  1173. return added, ErrVoteHeightMismatch
  1174. }
  1175. added, err = cs.LastCommit.AddVote(vote)
  1176. if !added {
  1177. return added, err
  1178. }
  1179. cs.Logger.Info(cmn.Fmt("Added to lastPrecommits: %v", cs.LastCommit.StringShort()))
  1180. cs.eventBus.PublishEventVote(types.EventDataVote{vote})
  1181. // if we can skip timeoutCommit and have all the votes now,
  1182. if cs.config.SkipTimeoutCommit && cs.LastCommit.HasAll() {
  1183. // go straight to new round (skip timeout commit)
  1184. // cs.scheduleTimeout(time.Duration(0), cs.Height, 0, cstypes.RoundStepNewHeight)
  1185. cs.enterNewRound(cs.Height, 0)
  1186. }
  1187. return
  1188. }
  1189. // Height mismatch is ignored.
  1190. // Not necessarily a bad peer, but not favourable behaviour.
  1191. if vote.Height != cs.Height {
  1192. err = ErrVoteHeightMismatch
  1193. cs.Logger.Info("Vote ignored and not added", "voteHeight", vote.Height, "csHeight", cs.Height, "err", err)
  1194. return
  1195. }
  1196. height := cs.Height
  1197. added, err = cs.Votes.AddVote(vote, peerID)
  1198. if !added {
  1199. // Either duplicate, or error upon cs.Votes.AddByIndex()
  1200. return
  1201. }
  1202. cs.eventBus.PublishEventVote(types.EventDataVote{vote})
  1203. switch vote.Type {
  1204. case types.VoteTypePrevote:
  1205. prevotes := cs.Votes.Prevotes(vote.Round)
  1206. cs.Logger.Info("Added to prevote", "vote", vote, "prevotes", prevotes.StringShort())
  1207. blockID, ok := prevotes.TwoThirdsMajority()
  1208. // First, unlock if prevotes is a valid POL.
  1209. // >> lockRound < POLRound <= unlockOrChangeLockRound (see spec)
  1210. // NOTE: If (lockRound < POLRound) but !(POLRound <= unlockOrChangeLockRound),
  1211. // we'll still enterNewRound(H,vote.R) and enterPrecommit(H,vote.R) to process it
  1212. // there.
  1213. if (cs.LockedBlock != nil) && (cs.LockedRound < vote.Round) && (vote.Round <= cs.Round) {
  1214. if ok && !cs.LockedBlock.HashesTo(blockID.Hash) {
  1215. cs.Logger.Info("Unlocking because of POL.", "lockedRound", cs.LockedRound, "POLRound", vote.Round)
  1216. cs.LockedRound = 0
  1217. cs.LockedBlock = nil
  1218. cs.LockedBlockParts = nil
  1219. cs.eventBus.PublishEventUnlock(cs.RoundStateEvent())
  1220. }
  1221. }
  1222. // Update ValidBlock
  1223. if ok && !blockID.IsZero() && !cs.ValidBlock.HashesTo(blockID.Hash) && vote.Round > cs.ValidRound {
  1224. // update valid value
  1225. if cs.ProposalBlock.HashesTo(blockID.Hash) {
  1226. cs.ValidRound = vote.Round
  1227. cs.ValidBlock = cs.ProposalBlock
  1228. cs.ValidBlockParts = cs.ProposalBlockParts
  1229. }
  1230. //TODO: We might want to update ValidBlock also in case we don't have that block yet,
  1231. // and obtain the required block using gossiping
  1232. }
  1233. if cs.Round <= vote.Round && prevotes.HasTwoThirdsAny() {
  1234. // Round-skip over to PrevoteWait or goto Precommit.
  1235. cs.enterNewRound(height, vote.Round) // if the vote is ahead of us
  1236. if prevotes.HasTwoThirdsMajority() {
  1237. cs.enterPrecommit(height, vote.Round)
  1238. } else {
  1239. cs.enterPrevote(height, vote.Round) // if the vote is ahead of us
  1240. cs.enterPrevoteWait(height, vote.Round)
  1241. }
  1242. } else if cs.Proposal != nil && 0 <= cs.Proposal.POLRound && cs.Proposal.POLRound == vote.Round {
  1243. // If the proposal is now complete, enter prevote of cs.Round.
  1244. if cs.isProposalComplete() {
  1245. cs.enterPrevote(height, cs.Round)
  1246. }
  1247. }
  1248. case types.VoteTypePrecommit:
  1249. precommits := cs.Votes.Precommits(vote.Round)
  1250. cs.Logger.Info("Added to precommit", "vote", vote, "precommits", precommits.StringShort())
  1251. blockID, ok := precommits.TwoThirdsMajority()
  1252. if ok {
  1253. if len(blockID.Hash) == 0 {
  1254. cs.enterNewRound(height, vote.Round+1)
  1255. } else {
  1256. cs.enterNewRound(height, vote.Round)
  1257. cs.enterPrecommit(height, vote.Round)
  1258. cs.enterCommit(height, vote.Round)
  1259. if cs.config.SkipTimeoutCommit && precommits.HasAll() {
  1260. // if we have all the votes now,
  1261. // go straight to new round (skip timeout commit)
  1262. // cs.scheduleTimeout(time.Duration(0), cs.Height, 0, cstypes.RoundStepNewHeight)
  1263. cs.enterNewRound(cs.Height, 0)
  1264. }
  1265. }
  1266. } else if cs.Round <= vote.Round && precommits.HasTwoThirdsAny() {
  1267. cs.enterNewRound(height, vote.Round)
  1268. cs.enterPrecommit(height, vote.Round)
  1269. cs.enterPrecommitWait(height, vote.Round)
  1270. }
  1271. default:
  1272. panic(cmn.Fmt("Unexpected vote type %X", vote.Type)) // go-wire should prevent this.
  1273. }
  1274. return
  1275. }
  1276. func (cs *ConsensusState) signVote(type_ byte, hash []byte, header types.PartSetHeader) (*types.Vote, error) {
  1277. addr := cs.privValidator.GetAddress()
  1278. valIndex, _ := cs.Validators.GetByAddress(addr)
  1279. vote := &types.Vote{
  1280. ValidatorAddress: addr,
  1281. ValidatorIndex: valIndex,
  1282. Height: cs.Height,
  1283. Round: cs.Round,
  1284. Timestamp: time.Now().UTC(),
  1285. Type: type_,
  1286. BlockID: types.BlockID{hash, header},
  1287. }
  1288. err := cs.privValidator.SignVote(cs.state.ChainID, vote)
  1289. return vote, err
  1290. }
  1291. // sign the vote and publish on internalMsgQueue
  1292. func (cs *ConsensusState) signAddVote(type_ byte, hash []byte, header types.PartSetHeader) *types.Vote {
  1293. // if we don't have a key or we're not in the validator set, do nothing
  1294. if cs.privValidator == nil || !cs.Validators.HasAddress(cs.privValidator.GetAddress()) {
  1295. return nil
  1296. }
  1297. vote, err := cs.signVote(type_, hash, header)
  1298. if err == nil {
  1299. cs.sendInternalMessage(msgInfo{&VoteMessage{vote}, ""})
  1300. cs.Logger.Info("Signed and pushed vote", "height", cs.Height, "round", cs.Round, "vote", vote, "err", err)
  1301. return vote
  1302. }
  1303. //if !cs.replayMode {
  1304. cs.Logger.Error("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "err", err)
  1305. //}
  1306. return nil
  1307. }
  1308. //---------------------------------------------------------
  1309. func CompareHRS(h1 int64, r1 int, s1 cstypes.RoundStepType, h2 int64, r2 int, s2 cstypes.RoundStepType) int {
  1310. if h1 < h2 {
  1311. return -1
  1312. } else if h1 > h2 {
  1313. return 1
  1314. }
  1315. if r1 < r2 {
  1316. return -1
  1317. } else if r1 > r2 {
  1318. return 1
  1319. }
  1320. if s1 < s2 {
  1321. return -1
  1322. } else if s1 > s2 {
  1323. return 1
  1324. }
  1325. return 0
  1326. }