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.

1737 lines
60 KiB

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