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.

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