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.

1732 lines
60 KiB

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