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.

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