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.

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