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.

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