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.

1414 lines
40 KiB

lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
10 years ago
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
add support for block pruning via ABCI Commit response (#4588) * Added BlockStore.DeleteBlock() * Added initial block pruner prototype * wip * Added BlockStore.PruneBlocks() * Added consensus setting for block pruning * Added BlockStore base * Error on replay if base does not have blocks * Handle missing blocks when sending VoteSetMaj23Message * Error message tweak * Properly update blockstore state * Error message fix again * blockchain: ignore peer missing blocks * Added FIXME * Added test for block replay with truncated history * Handle peer base in blockchain reactor * Improved replay error handling * Added tests for Store.PruneBlocks() * Fix non-RPC handling of truncated block history * Panic on missing block meta in needProofBlock() * Updated changelog * Handle truncated block history in RPC layer * Added info about earliest block in /status RPC * Reorder height and base in blockchain reactor messages * Updated changelog * Fix tests * Appease linter * Minor review fixes * Non-empty BlockStores should always have base > 0 * Update code to assume base > 0 invariant * Added blockstore tests for pruning to 0 * Make sure we don't prune below the current base * Added BlockStore.Size() * config: added retain_blocks recommendations * Update v1 blockchain reactor to handle blockstore base * Added state database pruning * Propagate errors on missing validator sets * Comment tweaks * Improved error message Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * use ABCI field ResponseCommit.retain_height instead of retain-blocks config option * remove State.RetainHeight, return value instead * fix minor issues * rename pruneHeights() to pruneBlocks() * noop to fix GitHub borkage Co-authored-by: Anton Kaliaev <anton.kalyaev@gmail.com>
5 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
7 years ago
fix data race Closes #1442 ``` WARNING: DATA RACE Write at 0x00c4209de7c8 by goroutine 23: github.com/tendermint/tendermint/types.(*Block).fillHeader() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:88 +0x157 github.com/tendermint/tendermint/types.(*Block).Hash() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:104 +0x121 github.com/tendermint/tendermint/types.(*Block).HashesTo() /home/vagrant/go/src/github.com/tendermint/tendermint/types/block.go:135 +0x4f github.com/tendermint/tendermint/consensus.(*ConsensusState).enterPrecommit() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1037 +0x182d github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1425 +0x1a6c github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:1318 +0x77 github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:581 +0x7a9 github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:539 +0x6c3 Previous read at 0x00c4209de7c8 by goroutine 47: github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*HexBytes).MarshalJSON() <autogenerated>:1 +0x52 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.invokeMarshalJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:433 +0x88 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:82 +0x8d2 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSONStruct() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:348 +0x539 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec)._encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:119 +0x83f github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).encodeReflectJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/json-encode.go:50 +0x10e github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino.(*Codec).MarshalJSON() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-amino/amino.go:296 +0x182 github.com/tendermint/tendermint/rpc/lib/types.NewRPCSuccessResponse() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/types/types.go:100 +0x12c github.com/tendermint/tendermint/rpc/lib/server.makeJSONRPCHandler.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/handlers.go:152 +0xab7 net/http.HandlerFunc.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:1918 +0x51 net/http.(*ServeMux).ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:2254 +0xa2 github.com/tendermint/tendermint/rpc/lib/server.RecoverAndLogHandler.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:138 +0x4fa net/http.HandlerFunc.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:1918 +0x51 net/http.serverHandler.ServeHTTP() /usr/lib/go-1.9/src/net/http/server.go:2619 +0xbc net/http.(*conn).serve() /usr/lib/go-1.9/src/net/http/server.go:1801 +0x83b Goroutine 23 (running) created at: github.com/tendermint/tendermint/consensus.(*ConsensusState).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/state.go:250 +0x35b github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/consensus.(*ConsensusReactor).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/consensus/reactor.go:69 +0x1b4 github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/consensus.(*ConsensusReactor).Start() <autogenerated>:1 +0x43 github.com/tendermint/tendermint/p2p.(*Switch).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch.go:177 +0x124 github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/node.(*Node).OnStart() /home/vagrant/go/src/github.com/tendermint/tendermint/node/node.go:416 +0xa1b github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common.(*BaseService).Start() /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/tmlibs/common/service.go:130 +0x5fc github.com/tendermint/tendermint/rpc/test.StartTendermint() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/test/helpers.go:100 +0x5b github.com/tendermint/tendermint/rpc/client_test.TestMain() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/client/main_test.go:17 +0x4c main.main() github.com/tendermint/tendermint/rpc/client/_test/_testmain.go:76 +0x1cd Goroutine 47 (running) created at: net/http.(*Server).Serve() /usr/lib/go-1.9/src/net/http/server.go:2720 +0x37c net/http.Serve() /usr/lib/go-1.9/src/net/http/server.go:2323 +0xe2 github.com/tendermint/tendermint/rpc/lib/server.StartHTTPServer.func1() /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/lib/server/http_server.go:35 +0xb3 ```
7 years ago
10 years ago
protect Record* peerStateStats functions by mutex Fixes #1414 DATA RACE: ``` Read at 0x00c4214ee940 by goroutine 146: github.com/tendermint/tendermint/consensus.(*peerStateStats).String() <autogenerated>:1 +0x57 fmt.(*pp).handleMethods() /usr/local/go/src/fmt/print.go:596 +0x3f4 fmt.(*pp).printArg() /usr/local/go/src/fmt/print.go:679 +0x11f fmt.(*pp).doPrintf() /usr/local/go/src/fmt/print.go:996 +0x319 fmt.Sprintf() /usr/local/go/src/fmt/print.go:196 +0x73 github.com/tendermint/tendermint/consensus.(*PeerState).StringIndented() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:1426 +0x573 github.com/tendermint/tendermint/consensus.(*PeerState).String() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:1419 +0x66 github.com/go-logfmt/logfmt.safeString() /home/ubuntu/go/src/github.com/go-logfmt/logfmt/encode.go:299 +0x9d github.com/go-logfmt/logfmt.writeValue() /home/ubuntu/go/src/github.com/go-logfmt/logfmt/encode.go:217 +0x5a0 github.com/go-logfmt/logfmt.(*Encoder).EncodeKeyval() /home/ubuntu/go/src/github.com/go-logfmt/logfmt/encode.go:61 +0x1dd github.com/tendermint/tmlibs/log.tmfmtLogger.Log() /home/ubuntu/go/src/github.com/tendermint/tmlibs/log/tmfmt_logger.go:107 +0x1001 github.com/tendermint/tmlibs/log.(*tmfmtLogger).Log() <autogenerated>:1 +0x93 github.com/go-kit/kit/log.(*context).Log() /home/ubuntu/go/src/github.com/go-kit/kit/log/log.go:124 +0x248 github.com/tendermint/tmlibs/log.(*tmLogger).Debug() /home/ubuntu/go/src/github.com/tendermint/tmlibs/log/tm_logger.go:64 +0x1d0 github.com/tendermint/tendermint/consensus.(*PeerState).PickSendVote() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:1059 +0x242 github.com/tendermint/tendermint/consensus.(*ConsensusReactor).gossipVotesForHeight() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:789 +0x6ef github.com/tendermint/tendermint/consensus.(*ConsensusReactor).gossipVotesRoutine() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:723 +0x1039 Previous write at 0x00c4214ee940 by goroutine 21: github.com/tendermint/tendermint/consensus.(*PeerState).RecordVote() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:1242 +0x15a github.com/tendermint/tendermint/consensus.(*ConsensusReactor).Receive() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:309 +0x32e6 github.com/tendermint/tendermint/p2p.createMConnection.func1() /home/ubuntu/go/src/github.com/tendermint/tendermint/p2p/peer.go:365 +0xea github.com/tendermint/tendermint/p2p/conn.(*MConnection).recvRoutine() /home/ubuntu/go/src/github.com/tendermint/tendermint/p2p/conn/connection.go:531 +0x779 ```
7 years ago
protect Record* peerStateStats functions by mutex Fixes #1414 DATA RACE: ``` Read at 0x00c4214ee940 by goroutine 146: github.com/tendermint/tendermint/consensus.(*peerStateStats).String() <autogenerated>:1 +0x57 fmt.(*pp).handleMethods() /usr/local/go/src/fmt/print.go:596 +0x3f4 fmt.(*pp).printArg() /usr/local/go/src/fmt/print.go:679 +0x11f fmt.(*pp).doPrintf() /usr/local/go/src/fmt/print.go:996 +0x319 fmt.Sprintf() /usr/local/go/src/fmt/print.go:196 +0x73 github.com/tendermint/tendermint/consensus.(*PeerState).StringIndented() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:1426 +0x573 github.com/tendermint/tendermint/consensus.(*PeerState).String() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:1419 +0x66 github.com/go-logfmt/logfmt.safeString() /home/ubuntu/go/src/github.com/go-logfmt/logfmt/encode.go:299 +0x9d github.com/go-logfmt/logfmt.writeValue() /home/ubuntu/go/src/github.com/go-logfmt/logfmt/encode.go:217 +0x5a0 github.com/go-logfmt/logfmt.(*Encoder).EncodeKeyval() /home/ubuntu/go/src/github.com/go-logfmt/logfmt/encode.go:61 +0x1dd github.com/tendermint/tmlibs/log.tmfmtLogger.Log() /home/ubuntu/go/src/github.com/tendermint/tmlibs/log/tmfmt_logger.go:107 +0x1001 github.com/tendermint/tmlibs/log.(*tmfmtLogger).Log() <autogenerated>:1 +0x93 github.com/go-kit/kit/log.(*context).Log() /home/ubuntu/go/src/github.com/go-kit/kit/log/log.go:124 +0x248 github.com/tendermint/tmlibs/log.(*tmLogger).Debug() /home/ubuntu/go/src/github.com/tendermint/tmlibs/log/tm_logger.go:64 +0x1d0 github.com/tendermint/tendermint/consensus.(*PeerState).PickSendVote() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:1059 +0x242 github.com/tendermint/tendermint/consensus.(*ConsensusReactor).gossipVotesForHeight() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:789 +0x6ef github.com/tendermint/tendermint/consensus.(*ConsensusReactor).gossipVotesRoutine() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:723 +0x1039 Previous write at 0x00c4214ee940 by goroutine 21: github.com/tendermint/tendermint/consensus.(*PeerState).RecordVote() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:1242 +0x15a github.com/tendermint/tendermint/consensus.(*ConsensusReactor).Receive() github.com/tendermint/tendermint/consensus/_test/_obj_test/reactor.go:309 +0x32e6 github.com/tendermint/tendermint/p2p.createMConnection.func1() /home/ubuntu/go/src/github.com/tendermint/tendermint/p2p/peer.go:365 +0xea github.com/tendermint/tendermint/p2p/conn.(*MConnection).recvRoutine() /home/ubuntu/go/src/github.com/tendermint/tendermint/p2p/conn/connection.go:531 +0x779 ```
7 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package consensus
  2. import (
  3. "fmt"
  4. "time"
  5. cstypes "github.com/tendermint/tendermint/internal/consensus/types"
  6. tmsync "github.com/tendermint/tendermint/internal/libs/sync"
  7. "github.com/tendermint/tendermint/internal/p2p"
  8. "github.com/tendermint/tendermint/libs/bits"
  9. tmevents "github.com/tendermint/tendermint/libs/events"
  10. "github.com/tendermint/tendermint/libs/log"
  11. "github.com/tendermint/tendermint/libs/service"
  12. tmcons "github.com/tendermint/tendermint/proto/tendermint/consensus"
  13. tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
  14. sm "github.com/tendermint/tendermint/state"
  15. "github.com/tendermint/tendermint/types"
  16. )
  17. var (
  18. _ service.Service = (*Reactor)(nil)
  19. _ p2p.Wrapper = (*tmcons.Message)(nil)
  20. // ChannelShims contains a map of ChannelDescriptorShim objects, where each
  21. // object wraps a reference to a legacy p2p ChannelDescriptor and the corresponding
  22. // p2p proto.Message the new p2p Channel is responsible for handling.
  23. //
  24. //
  25. // TODO: Remove once p2p refactor is complete.
  26. // ref: https://github.com/tendermint/tendermint/issues/5670
  27. ChannelShims = map[p2p.ChannelID]*p2p.ChannelDescriptorShim{
  28. StateChannel: {
  29. MsgType: new(tmcons.Message),
  30. Descriptor: &p2p.ChannelDescriptor{
  31. ID: byte(StateChannel),
  32. Priority: 8,
  33. SendQueueCapacity: 64,
  34. RecvMessageCapacity: maxMsgSize,
  35. RecvBufferCapacity: 128,
  36. MaxSendBytes: 12000,
  37. },
  38. },
  39. DataChannel: {
  40. MsgType: new(tmcons.Message),
  41. Descriptor: &p2p.ChannelDescriptor{
  42. // TODO: Consider a split between gossiping current block and catchup
  43. // stuff. Once we gossip the whole block there is nothing left to send
  44. // until next height or round.
  45. ID: byte(DataChannel),
  46. Priority: 12,
  47. SendQueueCapacity: 64,
  48. RecvBufferCapacity: 512,
  49. RecvMessageCapacity: maxMsgSize,
  50. MaxSendBytes: 40000,
  51. },
  52. },
  53. VoteChannel: {
  54. MsgType: new(tmcons.Message),
  55. Descriptor: &p2p.ChannelDescriptor{
  56. ID: byte(VoteChannel),
  57. Priority: 10,
  58. SendQueueCapacity: 64,
  59. RecvBufferCapacity: 128,
  60. RecvMessageCapacity: maxMsgSize,
  61. MaxSendBytes: 150,
  62. },
  63. },
  64. VoteSetBitsChannel: {
  65. MsgType: new(tmcons.Message),
  66. Descriptor: &p2p.ChannelDescriptor{
  67. ID: byte(VoteSetBitsChannel),
  68. Priority: 5,
  69. SendQueueCapacity: 8,
  70. RecvBufferCapacity: 128,
  71. RecvMessageCapacity: maxMsgSize,
  72. MaxSendBytes: 50,
  73. },
  74. },
  75. }
  76. )
  77. const (
  78. StateChannel = p2p.ChannelID(0x20)
  79. DataChannel = p2p.ChannelID(0x21)
  80. VoteChannel = p2p.ChannelID(0x22)
  81. VoteSetBitsChannel = p2p.ChannelID(0x23)
  82. maxMsgSize = 1048576 // 1MB; NOTE: keep in sync with types.PartSet sizes.
  83. blocksToContributeToBecomeGoodPeer = 10000
  84. votesToContributeToBecomeGoodPeer = 10000
  85. listenerIDConsensus = "consensus-reactor"
  86. )
  87. type ReactorOption func(*Reactor)
  88. // Temporary interface for switching to fast sync, we should get rid of v0.
  89. // See: https://github.com/tendermint/tendermint/issues/4595
  90. type FastSyncReactor interface {
  91. SwitchToFastSync(sm.State) error
  92. GetMaxPeerBlockHeight() int64
  93. }
  94. // Reactor defines a reactor for the consensus service.
  95. type Reactor struct {
  96. service.BaseService
  97. state *State
  98. eventBus *types.EventBus
  99. Metrics *Metrics
  100. mtx tmsync.RWMutex
  101. peers map[types.NodeID]*PeerState
  102. waitSync bool
  103. stateCh *p2p.Channel
  104. dataCh *p2p.Channel
  105. voteCh *p2p.Channel
  106. voteSetBitsCh *p2p.Channel
  107. peerUpdates *p2p.PeerUpdates
  108. // NOTE: We need a dedicated stateCloseCh channel for signaling closure of
  109. // the StateChannel due to the fact that the StateChannel message handler
  110. // performs a send on the VoteSetBitsChannel. This is an antipattern, so having
  111. // this dedicated channel,stateCloseCh, is necessary in order to avoid data races.
  112. stateCloseCh chan struct{}
  113. closeCh chan struct{}
  114. }
  115. // NewReactor returns a reference to a new consensus reactor, which implements
  116. // the service.Service interface. It accepts a logger, consensus state, references
  117. // to relevant p2p Channels and a channel to listen for peer updates on. The
  118. // reactor will close all p2p Channels when stopping.
  119. func NewReactor(
  120. logger log.Logger,
  121. cs *State,
  122. stateCh *p2p.Channel,
  123. dataCh *p2p.Channel,
  124. voteCh *p2p.Channel,
  125. voteSetBitsCh *p2p.Channel,
  126. peerUpdates *p2p.PeerUpdates,
  127. waitSync bool,
  128. options ...ReactorOption,
  129. ) *Reactor {
  130. r := &Reactor{
  131. state: cs,
  132. waitSync: waitSync,
  133. peers: make(map[types.NodeID]*PeerState),
  134. Metrics: NopMetrics(),
  135. stateCh: stateCh,
  136. dataCh: dataCh,
  137. voteCh: voteCh,
  138. voteSetBitsCh: voteSetBitsCh,
  139. peerUpdates: peerUpdates,
  140. stateCloseCh: make(chan struct{}),
  141. closeCh: make(chan struct{}),
  142. }
  143. r.BaseService = *service.NewBaseService(logger, "Consensus", r)
  144. for _, opt := range options {
  145. opt(r)
  146. }
  147. return r
  148. }
  149. // OnStart starts separate go routines for each p2p Channel and listens for
  150. // envelopes on each. In addition, it also listens for peer updates and handles
  151. // messages on that p2p channel accordingly. The caller must be sure to execute
  152. // OnStop to ensure the outbound p2p Channels are closed.
  153. func (r *Reactor) OnStart() error {
  154. r.Logger.Debug("consensus wait sync", "wait_sync", r.WaitSync())
  155. // start routine that computes peer statistics for evaluating peer quality
  156. //
  157. // TODO: Evaluate if we need this to be synchronized via WaitGroup as to not
  158. // leak the goroutine when stopping the reactor.
  159. go r.peerStatsRoutine()
  160. r.subscribeToBroadcastEvents()
  161. if !r.WaitSync() {
  162. if err := r.state.Start(); err != nil {
  163. return err
  164. }
  165. }
  166. go r.processStateCh()
  167. go r.processDataCh()
  168. go r.processVoteCh()
  169. go r.processVoteSetBitsCh()
  170. go r.processPeerUpdates()
  171. return nil
  172. }
  173. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  174. // blocking until they all exit, as well as unsubscribing from events and stopping
  175. // state.
  176. func (r *Reactor) OnStop() {
  177. r.unsubscribeFromBroadcastEvents()
  178. if err := r.state.Stop(); err != nil {
  179. r.Logger.Error("failed to stop consensus state", "err", err)
  180. }
  181. if !r.WaitSync() {
  182. r.state.Wait()
  183. }
  184. r.mtx.Lock()
  185. peers := r.peers
  186. r.mtx.Unlock()
  187. // wait for all spawned peer goroutines to gracefully exit
  188. for _, ps := range peers {
  189. ps.closer.Close()
  190. }
  191. for _, ps := range peers {
  192. ps.broadcastWG.Wait()
  193. }
  194. // Close the StateChannel goroutine separately since it uses its own channel
  195. // to signal closure.
  196. close(r.stateCloseCh)
  197. <-r.stateCh.Done()
  198. // Close closeCh to signal to all spawned goroutines to gracefully exit. All
  199. // p2p Channels should execute Close().
  200. close(r.closeCh)
  201. // Wait for all p2p Channels to be closed before returning. This ensures we
  202. // can easily reason about synchronization of all p2p Channels and ensure no
  203. // panics will occur.
  204. <-r.voteSetBitsCh.Done()
  205. <-r.dataCh.Done()
  206. <-r.voteCh.Done()
  207. <-r.peerUpdates.Done()
  208. }
  209. // SetEventBus sets the reactor's event bus.
  210. func (r *Reactor) SetEventBus(b *types.EventBus) {
  211. r.eventBus = b
  212. r.state.SetEventBus(b)
  213. }
  214. // WaitSync returns whether the consensus reactor is waiting for state/fast sync.
  215. func (r *Reactor) WaitSync() bool {
  216. r.mtx.RLock()
  217. defer r.mtx.RUnlock()
  218. return r.waitSync
  219. }
  220. // ReactorMetrics sets the reactor's metrics as an option function.
  221. func ReactorMetrics(metrics *Metrics) ReactorOption {
  222. return func(r *Reactor) { r.Metrics = metrics }
  223. }
  224. // SwitchToConsensus switches from fast-sync mode to consensus mode. It resets
  225. // the state, turns off fast-sync, and starts the consensus state-machine.
  226. func (r *Reactor) SwitchToConsensus(state sm.State, skipWAL bool) {
  227. r.Logger.Info("switching to consensus")
  228. // we have no votes, so reconstruct LastCommit from SeenCommit
  229. if state.LastBlockHeight > 0 {
  230. r.state.reconstructLastCommit(state)
  231. }
  232. // NOTE: The line below causes broadcastNewRoundStepRoutine() to broadcast a
  233. // NewRoundStepMessage.
  234. r.state.updateToState(state)
  235. r.mtx.Lock()
  236. r.waitSync = false
  237. r.mtx.Unlock()
  238. r.Metrics.FastSyncing.Set(0)
  239. r.Metrics.StateSyncing.Set(0)
  240. if skipWAL {
  241. r.state.doWALCatchup = false
  242. }
  243. if err := r.state.Start(); err != nil {
  244. panic(fmt.Sprintf(`failed to start consensus state: %v
  245. conS:
  246. %+v
  247. conR:
  248. %+v`, err, r.state, r))
  249. }
  250. }
  251. // String returns a string representation of the Reactor.
  252. //
  253. // NOTE: For now, it is just a hard-coded string to avoid accessing unprotected
  254. // shared variables.
  255. //
  256. // TODO: improve!
  257. func (r *Reactor) String() string {
  258. return "ConsensusReactor"
  259. }
  260. // StringIndented returns an indented string representation of the Reactor.
  261. func (r *Reactor) StringIndented(indent string) string {
  262. r.mtx.RLock()
  263. defer r.mtx.RUnlock()
  264. s := "ConsensusReactor{\n"
  265. s += indent + " " + r.state.StringIndented(indent+" ") + "\n"
  266. for _, ps := range r.peers {
  267. s += indent + " " + ps.StringIndented(indent+" ") + "\n"
  268. }
  269. s += indent + "}"
  270. return s
  271. }
  272. // GetPeerState returns PeerState for a given NodeID.
  273. func (r *Reactor) GetPeerState(peerID types.NodeID) (*PeerState, bool) {
  274. r.mtx.RLock()
  275. defer r.mtx.RUnlock()
  276. ps, ok := r.peers[peerID]
  277. return ps, ok
  278. }
  279. func (r *Reactor) broadcastNewRoundStepMessage(rs *cstypes.RoundState) {
  280. r.stateCh.Out <- p2p.Envelope{
  281. Broadcast: true,
  282. Message: makeRoundStepMessage(rs),
  283. }
  284. }
  285. func (r *Reactor) broadcastNewValidBlockMessage(rs *cstypes.RoundState) {
  286. psHeader := rs.ProposalBlockParts.Header()
  287. r.stateCh.Out <- p2p.Envelope{
  288. Broadcast: true,
  289. Message: &tmcons.NewValidBlock{
  290. Height: rs.Height,
  291. Round: rs.Round,
  292. BlockPartSetHeader: psHeader.ToProto(),
  293. BlockParts: rs.ProposalBlockParts.BitArray().ToProto(),
  294. IsCommit: rs.Step == cstypes.RoundStepCommit,
  295. },
  296. }
  297. }
  298. func (r *Reactor) broadcastHasVoteMessage(vote *types.Vote) {
  299. r.stateCh.Out <- p2p.Envelope{
  300. Broadcast: true,
  301. Message: &tmcons.HasVote{
  302. Height: vote.Height,
  303. Round: vote.Round,
  304. Type: vote.Type,
  305. Index: vote.ValidatorIndex,
  306. },
  307. }
  308. }
  309. // subscribeToBroadcastEvents subscribes for new round steps and votes using the
  310. // internal pubsub defined in the consensus state to broadcast them to peers
  311. // upon receiving.
  312. func (r *Reactor) subscribeToBroadcastEvents() {
  313. err := r.state.evsw.AddListenerForEvent(
  314. listenerIDConsensus,
  315. types.EventNewRoundStep,
  316. func(data tmevents.EventData) {
  317. r.broadcastNewRoundStepMessage(data.(*cstypes.RoundState))
  318. select {
  319. case r.state.onStopCh <- data.(*cstypes.RoundState):
  320. default:
  321. }
  322. },
  323. )
  324. if err != nil {
  325. r.Logger.Error("failed to add listener for events", "err", err)
  326. }
  327. err = r.state.evsw.AddListenerForEvent(
  328. listenerIDConsensus,
  329. types.EventValidBlock,
  330. func(data tmevents.EventData) {
  331. r.broadcastNewValidBlockMessage(data.(*cstypes.RoundState))
  332. },
  333. )
  334. if err != nil {
  335. r.Logger.Error("failed to add listener for events", "err", err)
  336. }
  337. err = r.state.evsw.AddListenerForEvent(
  338. listenerIDConsensus,
  339. types.EventVote,
  340. func(data tmevents.EventData) {
  341. r.broadcastHasVoteMessage(data.(*types.Vote))
  342. },
  343. )
  344. if err != nil {
  345. r.Logger.Error("failed to add listener for events", "err", err)
  346. }
  347. }
  348. func (r *Reactor) unsubscribeFromBroadcastEvents() {
  349. r.state.evsw.RemoveListener(listenerIDConsensus)
  350. }
  351. func makeRoundStepMessage(rs *cstypes.RoundState) *tmcons.NewRoundStep {
  352. return &tmcons.NewRoundStep{
  353. Height: rs.Height,
  354. Round: rs.Round,
  355. Step: uint32(rs.Step),
  356. SecondsSinceStartTime: int64(time.Since(rs.StartTime).Seconds()),
  357. LastCommitRound: rs.LastCommit.GetRound(),
  358. }
  359. }
  360. func (r *Reactor) sendNewRoundStepMessage(peerID types.NodeID) {
  361. rs := r.state.GetRoundState()
  362. msg := makeRoundStepMessage(rs)
  363. r.stateCh.Out <- p2p.Envelope{
  364. To: peerID,
  365. Message: msg,
  366. }
  367. }
  368. func (r *Reactor) gossipDataForCatchup(rs *cstypes.RoundState, prs *cstypes.PeerRoundState, ps *PeerState) {
  369. logger := r.Logger.With("height", prs.Height).With("peer", ps.peerID)
  370. if index, ok := prs.ProposalBlockParts.Not().PickRandom(); ok {
  371. // ensure that the peer's PartSetHeader is correct
  372. blockMeta := r.state.blockStore.LoadBlockMeta(prs.Height)
  373. if blockMeta == nil {
  374. logger.Error(
  375. "failed to load block meta",
  376. "our_height", rs.Height,
  377. "blockstore_base", r.state.blockStore.Base(),
  378. "blockstore_height", r.state.blockStore.Height(),
  379. )
  380. time.Sleep(r.state.config.PeerGossipSleepDuration)
  381. return
  382. } else if !blockMeta.BlockID.PartSetHeader.Equals(prs.ProposalBlockPartSetHeader) {
  383. logger.Info(
  384. "peer ProposalBlockPartSetHeader mismatch; sleeping",
  385. "block_part_set_header", blockMeta.BlockID.PartSetHeader,
  386. "peer_block_part_set_header", prs.ProposalBlockPartSetHeader,
  387. )
  388. time.Sleep(r.state.config.PeerGossipSleepDuration)
  389. return
  390. }
  391. part := r.state.blockStore.LoadBlockPart(prs.Height, index)
  392. if part == nil {
  393. logger.Error(
  394. "failed to load block part",
  395. "index", index,
  396. "block_part_set_header", blockMeta.BlockID.PartSetHeader,
  397. "peer_block_part_set_header", prs.ProposalBlockPartSetHeader,
  398. )
  399. time.Sleep(r.state.config.PeerGossipSleepDuration)
  400. return
  401. }
  402. partProto, err := part.ToProto()
  403. if err != nil {
  404. logger.Error("failed to convert block part to proto", "err", err)
  405. time.Sleep(r.state.config.PeerGossipSleepDuration)
  406. return
  407. }
  408. logger.Debug("sending block part for catchup", "round", prs.Round, "index", index)
  409. r.dataCh.Out <- p2p.Envelope{
  410. To: ps.peerID,
  411. Message: &tmcons.BlockPart{
  412. Height: prs.Height, // not our height, so it does not matter.
  413. Round: prs.Round, // not our height, so it does not matter
  414. Part: *partProto,
  415. },
  416. }
  417. return
  418. }
  419. time.Sleep(r.state.config.PeerGossipSleepDuration)
  420. }
  421. func (r *Reactor) gossipDataRoutine(ps *PeerState) {
  422. logger := r.Logger.With("peer", ps.peerID)
  423. defer ps.broadcastWG.Done()
  424. OUTER_LOOP:
  425. for {
  426. if !r.IsRunning() {
  427. return
  428. }
  429. select {
  430. case <-ps.closer.Done():
  431. // The peer is marked for removal via a PeerUpdate as the doneCh was
  432. // explicitly closed to signal we should exit.
  433. return
  434. default:
  435. }
  436. rs := r.state.GetRoundState()
  437. prs := ps.GetRoundState()
  438. // Send proposal Block parts?
  439. if rs.ProposalBlockParts.HasHeader(prs.ProposalBlockPartSetHeader) {
  440. if index, ok := rs.ProposalBlockParts.BitArray().Sub(prs.ProposalBlockParts.Copy()).PickRandom(); ok {
  441. part := rs.ProposalBlockParts.GetPart(index)
  442. partProto, err := part.ToProto()
  443. if err != nil {
  444. logger.Error("failed to convert block part to proto", "err", err)
  445. return
  446. }
  447. logger.Debug("sending block part", "height", prs.Height, "round", prs.Round)
  448. r.dataCh.Out <- p2p.Envelope{
  449. To: ps.peerID,
  450. Message: &tmcons.BlockPart{
  451. Height: rs.Height, // this tells peer that this part applies to us
  452. Round: rs.Round, // this tells peer that this part applies to us
  453. Part: *partProto,
  454. },
  455. }
  456. ps.SetHasProposalBlockPart(prs.Height, prs.Round, index)
  457. continue OUTER_LOOP
  458. }
  459. }
  460. // if the peer is on a previous height that we have, help catch up
  461. blockStoreBase := r.state.blockStore.Base()
  462. if blockStoreBase > 0 && 0 < prs.Height && prs.Height < rs.Height && prs.Height >= blockStoreBase {
  463. heightLogger := logger.With("height", prs.Height)
  464. // If we never received the commit message from the peer, the block parts
  465. // will not be initialized.
  466. if prs.ProposalBlockParts == nil {
  467. blockMeta := r.state.blockStore.LoadBlockMeta(prs.Height)
  468. if blockMeta == nil {
  469. heightLogger.Error(
  470. "failed to load block meta",
  471. "blockstoreBase", blockStoreBase,
  472. "blockstoreHeight", r.state.blockStore.Height(),
  473. )
  474. time.Sleep(r.state.config.PeerGossipSleepDuration)
  475. } else {
  476. ps.InitProposalBlockParts(blockMeta.BlockID.PartSetHeader)
  477. }
  478. // Continue the loop since prs is a copy and not effected by this
  479. // initialization.
  480. continue OUTER_LOOP
  481. }
  482. r.gossipDataForCatchup(rs, prs, ps)
  483. continue OUTER_LOOP
  484. }
  485. // if height and round don't match, sleep
  486. if (rs.Height != prs.Height) || (rs.Round != prs.Round) {
  487. time.Sleep(r.state.config.PeerGossipSleepDuration)
  488. continue OUTER_LOOP
  489. }
  490. // By here, height and round match.
  491. // Proposal block parts were already matched and sent if any were wanted.
  492. // (These can match on hash so the round doesn't matter)
  493. // Now consider sending other things, like the Proposal itself.
  494. // Send Proposal && ProposalPOL BitArray?
  495. if rs.Proposal != nil && !prs.Proposal {
  496. // Proposal: share the proposal metadata with peer.
  497. {
  498. propProto := rs.Proposal.ToProto()
  499. logger.Debug("sending proposal", "height", prs.Height, "round", prs.Round)
  500. r.dataCh.Out <- p2p.Envelope{
  501. To: ps.peerID,
  502. Message: &tmcons.Proposal{
  503. Proposal: *propProto,
  504. },
  505. }
  506. // NOTE: A peer might have received a different proposal message, so
  507. // this Proposal msg will be rejected!
  508. ps.SetHasProposal(rs.Proposal)
  509. }
  510. // ProposalPOL: lets peer know which POL votes we have so far. The peer
  511. // must receive ProposalMessage first. Note, rs.Proposal was validated,
  512. // so rs.Proposal.POLRound <= rs.Round, so we definitely have
  513. // rs.Votes.Prevotes(rs.Proposal.POLRound).
  514. if 0 <= rs.Proposal.POLRound {
  515. pPol := rs.Votes.Prevotes(rs.Proposal.POLRound).BitArray()
  516. pPolProto := pPol.ToProto()
  517. logger.Debug("sending POL", "height", prs.Height, "round", prs.Round)
  518. r.dataCh.Out <- p2p.Envelope{
  519. To: ps.peerID,
  520. Message: &tmcons.ProposalPOL{
  521. Height: rs.Height,
  522. ProposalPolRound: rs.Proposal.POLRound,
  523. ProposalPol: *pPolProto,
  524. },
  525. }
  526. }
  527. continue OUTER_LOOP
  528. }
  529. // nothing to do -- sleep
  530. time.Sleep(r.state.config.PeerGossipSleepDuration)
  531. continue OUTER_LOOP
  532. }
  533. }
  534. // pickSendVote picks a vote and sends it to the peer. It will return true if
  535. // there is a vote to send and false otherwise.
  536. func (r *Reactor) pickSendVote(ps *PeerState, votes types.VoteSetReader) bool {
  537. if vote, ok := ps.PickVoteToSend(votes); ok {
  538. r.Logger.Debug("sending vote message", "ps", ps, "vote", vote)
  539. r.voteCh.Out <- p2p.Envelope{
  540. To: ps.peerID,
  541. Message: &tmcons.Vote{
  542. Vote: vote.ToProto(),
  543. },
  544. }
  545. ps.SetHasVote(vote)
  546. return true
  547. }
  548. return false
  549. }
  550. func (r *Reactor) gossipVotesForHeight(rs *cstypes.RoundState, prs *cstypes.PeerRoundState, ps *PeerState) bool {
  551. logger := r.Logger.With("height", prs.Height).With("peer", ps.peerID)
  552. // if there are lastCommits to send...
  553. if prs.Step == cstypes.RoundStepNewHeight {
  554. if r.pickSendVote(ps, rs.LastCommit) {
  555. logger.Debug("picked rs.LastCommit to send")
  556. return true
  557. }
  558. }
  559. // if there are POL prevotes to send...
  560. if prs.Step <= cstypes.RoundStepPropose && prs.Round != -1 && prs.Round <= rs.Round && prs.ProposalPOLRound != -1 {
  561. if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
  562. if r.pickSendVote(ps, polPrevotes) {
  563. logger.Debug("picked rs.Prevotes(prs.ProposalPOLRound) to send", "round", prs.ProposalPOLRound)
  564. return true
  565. }
  566. }
  567. }
  568. // if there are prevotes to send...
  569. if prs.Step <= cstypes.RoundStepPrevoteWait && prs.Round != -1 && prs.Round <= rs.Round {
  570. if r.pickSendVote(ps, rs.Votes.Prevotes(prs.Round)) {
  571. logger.Debug("picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
  572. return true
  573. }
  574. }
  575. // if there are precommits to send...
  576. if prs.Step <= cstypes.RoundStepPrecommitWait && prs.Round != -1 && prs.Round <= rs.Round {
  577. if r.pickSendVote(ps, rs.Votes.Precommits(prs.Round)) {
  578. logger.Debug("picked rs.Precommits(prs.Round) to send", "round", prs.Round)
  579. return true
  580. }
  581. }
  582. // if there are prevotes to send...(which are needed because of validBlock mechanism)
  583. if prs.Round != -1 && prs.Round <= rs.Round {
  584. if r.pickSendVote(ps, rs.Votes.Prevotes(prs.Round)) {
  585. logger.Debug("picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
  586. return true
  587. }
  588. }
  589. // if there are POLPrevotes to send...
  590. if prs.ProposalPOLRound != -1 {
  591. if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
  592. if r.pickSendVote(ps, polPrevotes) {
  593. logger.Debug("picked rs.Prevotes(prs.ProposalPOLRound) to send", "round", prs.ProposalPOLRound)
  594. return true
  595. }
  596. }
  597. }
  598. return false
  599. }
  600. func (r *Reactor) gossipVotesRoutine(ps *PeerState) {
  601. logger := r.Logger.With("peer", ps.peerID)
  602. defer ps.broadcastWG.Done()
  603. // XXX: simple hack to throttle logs upon sleep
  604. logThrottle := 0
  605. OUTER_LOOP:
  606. for {
  607. if !r.IsRunning() {
  608. return
  609. }
  610. select {
  611. case <-ps.closer.Done():
  612. // The peer is marked for removal via a PeerUpdate as the doneCh was
  613. // explicitly closed to signal we should exit.
  614. return
  615. default:
  616. }
  617. rs := r.state.GetRoundState()
  618. prs := ps.GetRoundState()
  619. switch logThrottle {
  620. case 1: // first sleep
  621. logThrottle = 2
  622. case 2: // no more sleep
  623. logThrottle = 0
  624. }
  625. // if height matches, then send LastCommit, Prevotes, and Precommits
  626. if rs.Height == prs.Height {
  627. if r.gossipVotesForHeight(rs, prs, ps) {
  628. continue OUTER_LOOP
  629. }
  630. }
  631. // special catchup logic -- if peer is lagging by height 1, send LastCommit
  632. if prs.Height != 0 && rs.Height == prs.Height+1 {
  633. if r.pickSendVote(ps, rs.LastCommit) {
  634. logger.Debug("picked rs.LastCommit to send", "height", prs.Height)
  635. continue OUTER_LOOP
  636. }
  637. }
  638. // catchup logic -- if peer is lagging by more than 1, send Commit
  639. blockStoreBase := r.state.blockStore.Base()
  640. if blockStoreBase > 0 && prs.Height != 0 && rs.Height >= prs.Height+2 && prs.Height >= blockStoreBase {
  641. // Load the block commit for prs.Height, which contains precommit
  642. // signatures for prs.Height.
  643. if commit := r.state.blockStore.LoadBlockCommit(prs.Height); commit != nil {
  644. if r.pickSendVote(ps, commit) {
  645. logger.Debug("picked Catchup commit to send", "height", prs.Height)
  646. continue OUTER_LOOP
  647. }
  648. }
  649. }
  650. if logThrottle == 0 {
  651. // we sent nothing -- sleep
  652. logThrottle = 1
  653. logger.Debug(
  654. "no votes to send; sleeping",
  655. "rs.Height", rs.Height,
  656. "prs.Height", prs.Height,
  657. "localPV", rs.Votes.Prevotes(rs.Round).BitArray(), "peerPV", prs.Prevotes,
  658. "localPC", rs.Votes.Precommits(rs.Round).BitArray(), "peerPC", prs.Precommits,
  659. )
  660. } else if logThrottle == 2 {
  661. logThrottle = 1
  662. }
  663. time.Sleep(r.state.config.PeerGossipSleepDuration)
  664. continue OUTER_LOOP
  665. }
  666. }
  667. // NOTE: `queryMaj23Routine` has a simple crude design since it only comes
  668. // into play for liveness when there's a signature DDoS attack happening.
  669. func (r *Reactor) queryMaj23Routine(ps *PeerState) {
  670. defer ps.broadcastWG.Done()
  671. OUTER_LOOP:
  672. for {
  673. if !r.IsRunning() {
  674. return
  675. }
  676. select {
  677. case <-ps.closer.Done():
  678. // The peer is marked for removal via a PeerUpdate as the doneCh was
  679. // explicitly closed to signal we should exit.
  680. return
  681. default:
  682. }
  683. // maybe send Height/Round/Prevotes
  684. {
  685. rs := r.state.GetRoundState()
  686. prs := ps.GetRoundState()
  687. if rs.Height == prs.Height {
  688. if maj23, ok := rs.Votes.Prevotes(prs.Round).TwoThirdsMajority(); ok {
  689. r.stateCh.Out <- p2p.Envelope{
  690. To: ps.peerID,
  691. Message: &tmcons.VoteSetMaj23{
  692. Height: prs.Height,
  693. Round: prs.Round,
  694. Type: tmproto.PrevoteType,
  695. BlockID: maj23.ToProto(),
  696. },
  697. }
  698. time.Sleep(r.state.config.PeerQueryMaj23SleepDuration)
  699. }
  700. }
  701. }
  702. // maybe send Height/Round/Precommits
  703. {
  704. rs := r.state.GetRoundState()
  705. prs := ps.GetRoundState()
  706. if rs.Height == prs.Height {
  707. if maj23, ok := rs.Votes.Precommits(prs.Round).TwoThirdsMajority(); ok {
  708. r.stateCh.Out <- p2p.Envelope{
  709. To: ps.peerID,
  710. Message: &tmcons.VoteSetMaj23{
  711. Height: prs.Height,
  712. Round: prs.Round,
  713. Type: tmproto.PrecommitType,
  714. BlockID: maj23.ToProto(),
  715. },
  716. }
  717. time.Sleep(r.state.config.PeerQueryMaj23SleepDuration)
  718. }
  719. }
  720. }
  721. // maybe send Height/Round/ProposalPOL
  722. {
  723. rs := r.state.GetRoundState()
  724. prs := ps.GetRoundState()
  725. if rs.Height == prs.Height && prs.ProposalPOLRound >= 0 {
  726. if maj23, ok := rs.Votes.Prevotes(prs.ProposalPOLRound).TwoThirdsMajority(); ok {
  727. r.stateCh.Out <- p2p.Envelope{
  728. To: ps.peerID,
  729. Message: &tmcons.VoteSetMaj23{
  730. Height: prs.Height,
  731. Round: prs.ProposalPOLRound,
  732. Type: tmproto.PrevoteType,
  733. BlockID: maj23.ToProto(),
  734. },
  735. }
  736. time.Sleep(r.state.config.PeerQueryMaj23SleepDuration)
  737. }
  738. }
  739. }
  740. // Little point sending LastCommitRound/LastCommit, these are fleeting and
  741. // non-blocking.
  742. // maybe send Height/CatchupCommitRound/CatchupCommit
  743. {
  744. prs := ps.GetRoundState()
  745. if prs.CatchupCommitRound != -1 && prs.Height > 0 && prs.Height <= r.state.blockStore.Height() &&
  746. prs.Height >= r.state.blockStore.Base() {
  747. if commit := r.state.LoadCommit(prs.Height); commit != nil {
  748. r.stateCh.Out <- p2p.Envelope{
  749. To: ps.peerID,
  750. Message: &tmcons.VoteSetMaj23{
  751. Height: prs.Height,
  752. Round: commit.Round,
  753. Type: tmproto.PrecommitType,
  754. BlockID: commit.BlockID.ToProto(),
  755. },
  756. }
  757. time.Sleep(r.state.config.PeerQueryMaj23SleepDuration)
  758. }
  759. }
  760. }
  761. time.Sleep(r.state.config.PeerQueryMaj23SleepDuration)
  762. continue OUTER_LOOP
  763. }
  764. }
  765. // processPeerUpdate process a peer update message. For new or reconnected peers,
  766. // we create a peer state if one does not exist for the peer, which should always
  767. // be the case, and we spawn all the relevant goroutine to broadcast messages to
  768. // the peer. During peer removal, we remove the peer for our set of peers and
  769. // signal to all spawned goroutines to gracefully exit in a non-blocking manner.
  770. func (r *Reactor) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
  771. r.Logger.Debug("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  772. r.mtx.Lock()
  773. defer r.mtx.Unlock()
  774. switch peerUpdate.Status {
  775. case p2p.PeerStatusUp:
  776. // Do not allow starting new broadcasting goroutines after reactor shutdown
  777. // has been initiated. This can happen after we've manually closed all
  778. // peer goroutines and closed r.closeCh, but the router still sends in-flight
  779. // peer updates.
  780. if !r.IsRunning() {
  781. return
  782. }
  783. var (
  784. ps *PeerState
  785. ok bool
  786. )
  787. ps, ok = r.peers[peerUpdate.NodeID]
  788. if !ok {
  789. ps = NewPeerState(r.Logger, peerUpdate.NodeID)
  790. r.peers[peerUpdate.NodeID] = ps
  791. }
  792. if !ps.IsRunning() {
  793. // Set the peer state's closer to signal to all spawned goroutines to exit
  794. // when the peer is removed. We also set the running state to ensure we
  795. // do not spawn multiple instances of the same goroutines and finally we
  796. // set the waitgroup counter so we know when all goroutines have exited.
  797. ps.broadcastWG.Add(3)
  798. ps.SetRunning(true)
  799. // start goroutines for this peer
  800. go r.gossipDataRoutine(ps)
  801. go r.gossipVotesRoutine(ps)
  802. go r.queryMaj23Routine(ps)
  803. // Send our state to the peer. If we're fast-syncing, broadcast a
  804. // RoundStepMessage later upon SwitchToConsensus().
  805. if !r.waitSync {
  806. go r.sendNewRoundStepMessage(ps.peerID)
  807. }
  808. }
  809. case p2p.PeerStatusDown:
  810. ps, ok := r.peers[peerUpdate.NodeID]
  811. if ok && ps.IsRunning() {
  812. // signal to all spawned goroutines for the peer to gracefully exit
  813. ps.closer.Close()
  814. go func() {
  815. // Wait for all spawned broadcast goroutines to exit before marking the
  816. // peer state as no longer running and removal from the peers map.
  817. ps.broadcastWG.Wait()
  818. r.mtx.Lock()
  819. delete(r.peers, peerUpdate.NodeID)
  820. r.mtx.Unlock()
  821. ps.SetRunning(false)
  822. }()
  823. }
  824. }
  825. }
  826. // handleStateMessage handles envelopes sent from peers on the StateChannel.
  827. // An error is returned if the message is unrecognized or if validation fails.
  828. // If we fail to find the peer state for the envelope sender, we perform a no-op
  829. // and return. This can happen when we process the envelope after the peer is
  830. // removed.
  831. func (r *Reactor) handleStateMessage(envelope p2p.Envelope, msgI Message) error {
  832. ps, ok := r.GetPeerState(envelope.From)
  833. if !ok || ps == nil {
  834. r.Logger.Debug("failed to find peer state", "peer", envelope.From, "ch_id", "StateChannel")
  835. return nil
  836. }
  837. switch msg := envelope.Message.(type) {
  838. case *tmcons.NewRoundStep:
  839. r.state.mtx.RLock()
  840. initialHeight := r.state.state.InitialHeight
  841. r.state.mtx.RUnlock()
  842. if err := msgI.(*NewRoundStepMessage).ValidateHeight(initialHeight); err != nil {
  843. r.Logger.Error("peer sent us an invalid msg", "msg", msg, "err", err)
  844. return err
  845. }
  846. ps.ApplyNewRoundStepMessage(msgI.(*NewRoundStepMessage))
  847. case *tmcons.NewValidBlock:
  848. ps.ApplyNewValidBlockMessage(msgI.(*NewValidBlockMessage))
  849. case *tmcons.HasVote:
  850. ps.ApplyHasVoteMessage(msgI.(*HasVoteMessage))
  851. case *tmcons.VoteSetMaj23:
  852. r.state.mtx.RLock()
  853. height, votes := r.state.Height, r.state.Votes
  854. r.state.mtx.RUnlock()
  855. if height != msg.Height {
  856. return nil
  857. }
  858. vsmMsg := msgI.(*VoteSetMaj23Message)
  859. // peer claims to have a maj23 for some BlockID at <H,R,S>
  860. err := votes.SetPeerMaj23(msg.Round, msg.Type, ps.peerID, vsmMsg.BlockID)
  861. if err != nil {
  862. return err
  863. }
  864. // Respond with a VoteSetBitsMessage showing which votes we have and
  865. // consequently shows which we don't have.
  866. var ourVotes *bits.BitArray
  867. switch vsmMsg.Type {
  868. case tmproto.PrevoteType:
  869. ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(vsmMsg.BlockID)
  870. case tmproto.PrecommitType:
  871. ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(vsmMsg.BlockID)
  872. default:
  873. panic("bad VoteSetBitsMessage field type; forgot to add a check in ValidateBasic?")
  874. }
  875. eMsg := &tmcons.VoteSetBits{
  876. Height: msg.Height,
  877. Round: msg.Round,
  878. Type: msg.Type,
  879. BlockID: msg.BlockID,
  880. }
  881. if votesProto := ourVotes.ToProto(); votesProto != nil {
  882. eMsg.Votes = *votesProto
  883. }
  884. r.voteSetBitsCh.Out <- p2p.Envelope{
  885. To: envelope.From,
  886. Message: eMsg,
  887. }
  888. default:
  889. return fmt.Errorf("received unknown message on StateChannel: %T", msg)
  890. }
  891. return nil
  892. }
  893. // handleDataMessage handles envelopes sent from peers on the DataChannel. If we
  894. // fail to find the peer state for the envelope sender, we perform a no-op and
  895. // return. This can happen when we process the envelope after the peer is
  896. // removed.
  897. func (r *Reactor) handleDataMessage(envelope p2p.Envelope, msgI Message) error {
  898. logger := r.Logger.With("peer", envelope.From, "ch_id", "DataChannel")
  899. ps, ok := r.GetPeerState(envelope.From)
  900. if !ok || ps == nil {
  901. r.Logger.Debug("failed to find peer state")
  902. return nil
  903. }
  904. if r.WaitSync() {
  905. logger.Info("ignoring message received during sync", "msg", msgI)
  906. return nil
  907. }
  908. switch msg := envelope.Message.(type) {
  909. case *tmcons.Proposal:
  910. pMsg := msgI.(*ProposalMessage)
  911. ps.SetHasProposal(pMsg.Proposal)
  912. r.state.peerMsgQueue <- msgInfo{pMsg, envelope.From}
  913. case *tmcons.ProposalPOL:
  914. ps.ApplyProposalPOLMessage(msgI.(*ProposalPOLMessage))
  915. case *tmcons.BlockPart:
  916. bpMsg := msgI.(*BlockPartMessage)
  917. ps.SetHasProposalBlockPart(bpMsg.Height, bpMsg.Round, int(bpMsg.Part.Index))
  918. r.Metrics.BlockParts.With("peer_id", string(envelope.From)).Add(1)
  919. r.state.peerMsgQueue <- msgInfo{bpMsg, envelope.From}
  920. default:
  921. return fmt.Errorf("received unknown message on DataChannel: %T", msg)
  922. }
  923. return nil
  924. }
  925. // handleVoteMessage handles envelopes sent from peers on the VoteChannel. If we
  926. // fail to find the peer state for the envelope sender, we perform a no-op and
  927. // return. This can happen when we process the envelope after the peer is
  928. // removed.
  929. func (r *Reactor) handleVoteMessage(envelope p2p.Envelope, msgI Message) error {
  930. logger := r.Logger.With("peer", envelope.From, "ch_id", "VoteChannel")
  931. ps, ok := r.GetPeerState(envelope.From)
  932. if !ok || ps == nil {
  933. r.Logger.Debug("failed to find peer state")
  934. return nil
  935. }
  936. if r.WaitSync() {
  937. logger.Info("ignoring message received during sync", "msg", msgI)
  938. return nil
  939. }
  940. switch msg := envelope.Message.(type) {
  941. case *tmcons.Vote:
  942. r.state.mtx.RLock()
  943. height, valSize, lastCommitSize := r.state.Height, r.state.Validators.Size(), r.state.LastCommit.Size()
  944. r.state.mtx.RUnlock()
  945. vMsg := msgI.(*VoteMessage)
  946. ps.EnsureVoteBitArrays(height, valSize)
  947. ps.EnsureVoteBitArrays(height-1, lastCommitSize)
  948. ps.SetHasVote(vMsg.Vote)
  949. r.state.peerMsgQueue <- msgInfo{vMsg, envelope.From}
  950. default:
  951. return fmt.Errorf("received unknown message on VoteChannel: %T", msg)
  952. }
  953. return nil
  954. }
  955. // handleVoteSetBitsMessage handles envelopes sent from peers on the
  956. // VoteSetBitsChannel. If we fail to find the peer state for the envelope sender,
  957. // we perform a no-op and return. This can happen when we process the envelope
  958. // after the peer is removed.
  959. func (r *Reactor) handleVoteSetBitsMessage(envelope p2p.Envelope, msgI Message) error {
  960. logger := r.Logger.With("peer", envelope.From, "ch_id", "VoteSetBitsChannel")
  961. ps, ok := r.GetPeerState(envelope.From)
  962. if !ok || ps == nil {
  963. r.Logger.Debug("failed to find peer state")
  964. return nil
  965. }
  966. if r.WaitSync() {
  967. logger.Info("ignoring message received during sync", "msg", msgI)
  968. return nil
  969. }
  970. switch msg := envelope.Message.(type) {
  971. case *tmcons.VoteSetBits:
  972. r.state.mtx.RLock()
  973. height, votes := r.state.Height, r.state.Votes
  974. r.state.mtx.RUnlock()
  975. vsbMsg := msgI.(*VoteSetBitsMessage)
  976. if height == msg.Height {
  977. var ourVotes *bits.BitArray
  978. switch msg.Type {
  979. case tmproto.PrevoteType:
  980. ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(vsbMsg.BlockID)
  981. case tmproto.PrecommitType:
  982. ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(vsbMsg.BlockID)
  983. default:
  984. panic("bad VoteSetBitsMessage field type; forgot to add a check in ValidateBasic?")
  985. }
  986. ps.ApplyVoteSetBitsMessage(vsbMsg, ourVotes)
  987. } else {
  988. ps.ApplyVoteSetBitsMessage(vsbMsg, nil)
  989. }
  990. default:
  991. return fmt.Errorf("received unknown message on VoteSetBitsChannel: %T", msg)
  992. }
  993. return nil
  994. }
  995. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  996. // It will handle errors and any possible panics gracefully. A caller can handle
  997. // any error returned by sending a PeerError on the respective channel.
  998. //
  999. // NOTE: We block on consensus state for proposals, block parts, and votes.
  1000. func (r *Reactor) handleMessage(chID p2p.ChannelID, envelope p2p.Envelope) (err error) {
  1001. defer func() {
  1002. if e := recover(); e != nil {
  1003. err = fmt.Errorf("panic in processing message: %v", e)
  1004. r.Logger.Error("recovering from processing message panic", "err", err)
  1005. }
  1006. }()
  1007. // Just skip the entire message during syncing so that we can
  1008. // process fewer messages.
  1009. if r.WaitSync() {
  1010. return
  1011. }
  1012. // We wrap the envelope's message in a Proto wire type so we can convert back
  1013. // the domain type that individual channel message handlers can work with. We
  1014. // do this here once to avoid having to do it for each individual message type.
  1015. // and because a large part of the core business logic depends on these
  1016. // domain types opposed to simply working with the Proto types.
  1017. protoMsg := new(tmcons.Message)
  1018. if err := protoMsg.Wrap(envelope.Message); err != nil {
  1019. return err
  1020. }
  1021. msgI, err := MsgFromProto(protoMsg)
  1022. if err != nil {
  1023. return err
  1024. }
  1025. r.Logger.Debug("received message", "ch_id", chID, "message", msgI, "peer", envelope.From)
  1026. switch chID {
  1027. case StateChannel:
  1028. err = r.handleStateMessage(envelope, msgI)
  1029. case DataChannel:
  1030. err = r.handleDataMessage(envelope, msgI)
  1031. case VoteChannel:
  1032. err = r.handleVoteMessage(envelope, msgI)
  1033. case VoteSetBitsChannel:
  1034. err = r.handleVoteSetBitsMessage(envelope, msgI)
  1035. default:
  1036. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  1037. }
  1038. return err
  1039. }
  1040. // processStateCh initiates a blocking process where we listen for and handle
  1041. // envelopes on the StateChannel. Any error encountered during message
  1042. // execution will result in a PeerError being sent on the StateChannel. When
  1043. // the reactor is stopped, we will catch the signal and close the p2p Channel
  1044. // gracefully.
  1045. func (r *Reactor) processStateCh() {
  1046. defer r.stateCh.Close()
  1047. for {
  1048. select {
  1049. case envelope := <-r.stateCh.In:
  1050. if err := r.handleMessage(r.stateCh.ID, envelope); err != nil {
  1051. r.Logger.Error("failed to process message", "ch_id", r.stateCh.ID, "envelope", envelope, "err", err)
  1052. r.stateCh.Error <- p2p.PeerError{
  1053. NodeID: envelope.From,
  1054. Err: err,
  1055. }
  1056. }
  1057. case <-r.stateCloseCh:
  1058. r.Logger.Debug("stopped listening on StateChannel; closing...")
  1059. return
  1060. }
  1061. }
  1062. }
  1063. // processDataCh initiates a blocking process where we listen for and handle
  1064. // envelopes on the DataChannel. Any error encountered during message
  1065. // execution will result in a PeerError being sent on the DataChannel. When
  1066. // the reactor is stopped, we will catch the signal and close the p2p Channel
  1067. // gracefully.
  1068. func (r *Reactor) processDataCh() {
  1069. defer r.dataCh.Close()
  1070. for {
  1071. select {
  1072. case envelope := <-r.dataCh.In:
  1073. if err := r.handleMessage(r.dataCh.ID, envelope); err != nil {
  1074. r.Logger.Error("failed to process message", "ch_id", r.dataCh.ID, "envelope", envelope, "err", err)
  1075. r.dataCh.Error <- p2p.PeerError{
  1076. NodeID: envelope.From,
  1077. Err: err,
  1078. }
  1079. }
  1080. case <-r.closeCh:
  1081. r.Logger.Debug("stopped listening on DataChannel; closing...")
  1082. return
  1083. }
  1084. }
  1085. }
  1086. // processVoteCh initiates a blocking process where we listen for and handle
  1087. // envelopes on the VoteChannel. Any error encountered during message
  1088. // execution will result in a PeerError being sent on the VoteChannel. When
  1089. // the reactor is stopped, we will catch the signal and close the p2p Channel
  1090. // gracefully.
  1091. func (r *Reactor) processVoteCh() {
  1092. defer r.voteCh.Close()
  1093. for {
  1094. select {
  1095. case envelope := <-r.voteCh.In:
  1096. if err := r.handleMessage(r.voteCh.ID, envelope); err != nil {
  1097. r.Logger.Error("failed to process message", "ch_id", r.voteCh.ID, "envelope", envelope, "err", err)
  1098. r.voteCh.Error <- p2p.PeerError{
  1099. NodeID: envelope.From,
  1100. Err: err,
  1101. }
  1102. }
  1103. case <-r.closeCh:
  1104. r.Logger.Debug("stopped listening on VoteChannel; closing...")
  1105. return
  1106. }
  1107. }
  1108. }
  1109. // processVoteCh initiates a blocking process where we listen for and handle
  1110. // envelopes on the VoteSetBitsChannel. Any error encountered during message
  1111. // execution will result in a PeerError being sent on the VoteSetBitsChannel.
  1112. // When the reactor is stopped, we will catch the signal and close the p2p
  1113. // Channel gracefully.
  1114. func (r *Reactor) processVoteSetBitsCh() {
  1115. defer r.voteSetBitsCh.Close()
  1116. for {
  1117. select {
  1118. case envelope := <-r.voteSetBitsCh.In:
  1119. if err := r.handleMessage(r.voteSetBitsCh.ID, envelope); err != nil {
  1120. r.Logger.Error("failed to process message", "ch_id", r.voteSetBitsCh.ID, "envelope", envelope, "err", err)
  1121. r.voteSetBitsCh.Error <- p2p.PeerError{
  1122. NodeID: envelope.From,
  1123. Err: err,
  1124. }
  1125. }
  1126. case <-r.closeCh:
  1127. r.Logger.Debug("stopped listening on VoteSetBitsChannel; closing...")
  1128. return
  1129. }
  1130. }
  1131. }
  1132. // processPeerUpdates initiates a blocking process where we listen for and handle
  1133. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  1134. // close the p2p PeerUpdatesCh gracefully.
  1135. func (r *Reactor) processPeerUpdates() {
  1136. defer r.peerUpdates.Close()
  1137. for {
  1138. select {
  1139. case peerUpdate := <-r.peerUpdates.Updates():
  1140. r.processPeerUpdate(peerUpdate)
  1141. case <-r.closeCh:
  1142. r.Logger.Debug("stopped listening on peer updates channel; closing...")
  1143. return
  1144. }
  1145. }
  1146. }
  1147. func (r *Reactor) peerStatsRoutine() {
  1148. for {
  1149. if !r.IsRunning() {
  1150. r.Logger.Info("stopping peerStatsRoutine")
  1151. return
  1152. }
  1153. select {
  1154. case msg := <-r.state.statsMsgQueue:
  1155. ps, ok := r.GetPeerState(msg.PeerID)
  1156. if !ok || ps == nil {
  1157. r.Logger.Debug("attempt to update stats for non-existent peer", "peer", msg.PeerID)
  1158. continue
  1159. }
  1160. switch msg.Msg.(type) {
  1161. case *VoteMessage:
  1162. if numVotes := ps.RecordVote(); numVotes%votesToContributeToBecomeGoodPeer == 0 {
  1163. r.peerUpdates.SendUpdate(p2p.PeerUpdate{
  1164. NodeID: msg.PeerID,
  1165. Status: p2p.PeerStatusGood,
  1166. })
  1167. }
  1168. case *BlockPartMessage:
  1169. if numParts := ps.RecordBlockPart(); numParts%blocksToContributeToBecomeGoodPeer == 0 {
  1170. r.peerUpdates.SendUpdate(p2p.PeerUpdate{
  1171. NodeID: msg.PeerID,
  1172. Status: p2p.PeerStatusGood,
  1173. })
  1174. }
  1175. }
  1176. case <-r.closeCh:
  1177. return
  1178. }
  1179. }
  1180. }
  1181. func (r *Reactor) GetConsensusState() *State {
  1182. return r.state
  1183. }