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.

1607 lines
56 KiB

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