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.

1592 lines
55 KiB

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