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.

1720 lines
59 KiB

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