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.

1569 lines
54 KiB

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