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.

1692 lines
58 KiB

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