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.

1388 lines
39 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
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
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>
4 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 ```
6 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 ```
6 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 ```
6 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/consensus/types"
  6. "github.com/tendermint/tendermint/libs/bits"
  7. tmevents "github.com/tendermint/tendermint/libs/events"
  8. "github.com/tendermint/tendermint/libs/log"
  9. "github.com/tendermint/tendermint/libs/service"
  10. tmsync "github.com/tendermint/tendermint/libs/sync"
  11. "github.com/tendermint/tendermint/p2p"
  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: 6,
  33. SendQueueCapacity: 100,
  34. RecvMessageCapacity: maxMsgSize,
  35. },
  36. },
  37. DataChannel: {
  38. MsgType: new(tmcons.Message),
  39. Descriptor: &p2p.ChannelDescriptor{
  40. // TODO: Consider a split between gossiping current block and catchup
  41. // stuff. Once we gossip the whole block there is nothing left to send
  42. // until next height or round.
  43. ID: byte(DataChannel),
  44. Priority: 10,
  45. SendQueueCapacity: 100,
  46. RecvBufferCapacity: 50 * 4096,
  47. RecvMessageCapacity: maxMsgSize,
  48. },
  49. },
  50. VoteChannel: {
  51. MsgType: new(tmcons.Message),
  52. Descriptor: &p2p.ChannelDescriptor{
  53. ID: byte(VoteChannel),
  54. Priority: 7,
  55. SendQueueCapacity: 100,
  56. RecvBufferCapacity: 100 * 100,
  57. RecvMessageCapacity: maxMsgSize,
  58. },
  59. },
  60. VoteSetBitsChannel: {
  61. MsgType: new(tmcons.Message),
  62. Descriptor: &p2p.ChannelDescriptor{
  63. ID: byte(VoteSetBitsChannel),
  64. Priority: 1,
  65. SendQueueCapacity: 2,
  66. RecvBufferCapacity: 1024,
  67. RecvMessageCapacity: maxMsgSize,
  68. },
  69. },
  70. }
  71. )
  72. const (
  73. StateChannel = p2p.ChannelID(0x20)
  74. DataChannel = p2p.ChannelID(0x21)
  75. VoteChannel = p2p.ChannelID(0x22)
  76. VoteSetBitsChannel = p2p.ChannelID(0x23)
  77. maxMsgSize = 1048576 // 1MB; NOTE: keep in sync with types.PartSet sizes.
  78. blocksToContributeToBecomeGoodPeer = 10000
  79. votesToContributeToBecomeGoodPeer = 10000
  80. listenerIDConsensus = "consensus-reactor"
  81. )
  82. type ReactorOption func(*Reactor)
  83. // Reactor defines a reactor for the consensus service.
  84. type Reactor struct {
  85. service.BaseService
  86. state *State
  87. eventBus *types.EventBus
  88. Metrics *Metrics
  89. mtx tmsync.RWMutex
  90. peers map[p2p.NodeID]*PeerState
  91. waitSync bool
  92. stateCh *p2p.Channel
  93. dataCh *p2p.Channel
  94. voteCh *p2p.Channel
  95. voteSetBitsCh *p2p.Channel
  96. peerUpdates *p2p.PeerUpdates
  97. // NOTE: We need a dedicated stateCloseCh channel for signaling closure of
  98. // the StateChannel due to the fact that the StateChannel message handler
  99. // performs a send on the VoteSetBitsChannel. This is an antipattern, so having
  100. // this dedicated channel,stateCloseCh, is necessary in order to avoid data races.
  101. stateCloseCh chan struct{}
  102. closeCh chan struct{}
  103. }
  104. // NewReactor returns a reference to a new consensus reactor, which implements
  105. // the service.Service interface. It accepts a logger, consensus state, references
  106. // to relevant p2p Channels and a channel to listen for peer updates on. The
  107. // reactor will close all p2p Channels when stopping.
  108. func NewReactor(
  109. logger log.Logger,
  110. cs *State,
  111. stateCh *p2p.Channel,
  112. dataCh *p2p.Channel,
  113. voteCh *p2p.Channel,
  114. voteSetBitsCh *p2p.Channel,
  115. peerUpdates *p2p.PeerUpdates,
  116. waitSync bool,
  117. options ...ReactorOption,
  118. ) *Reactor {
  119. r := &Reactor{
  120. state: cs,
  121. waitSync: waitSync,
  122. peers: make(map[p2p.NodeID]*PeerState),
  123. Metrics: NopMetrics(),
  124. stateCh: stateCh,
  125. dataCh: dataCh,
  126. voteCh: voteCh,
  127. voteSetBitsCh: voteSetBitsCh,
  128. peerUpdates: peerUpdates,
  129. stateCloseCh: make(chan struct{}),
  130. closeCh: make(chan struct{}),
  131. }
  132. r.BaseService = *service.NewBaseService(logger, "Consensus", r)
  133. for _, opt := range options {
  134. opt(r)
  135. }
  136. return r
  137. }
  138. // OnStart starts separate go routines for each p2p Channel and listens for
  139. // envelopes on each. In addition, it also listens for peer updates and handles
  140. // messages on that p2p channel accordingly. The caller must be sure to execute
  141. // OnStop to ensure the outbound p2p Channels are closed.
  142. func (r *Reactor) OnStart() error {
  143. r.Logger.Debug("consensus wait sync", "wait_sync", r.WaitSync())
  144. // start routine that computes peer statistics for evaluating peer quality
  145. //
  146. // TODO: Evaluate if we need this to be synchronized via WaitGroup as to not
  147. // leak the goroutine when stopping the reactor.
  148. go r.peerStatsRoutine()
  149. r.subscribeToBroadcastEvents()
  150. if !r.WaitSync() {
  151. if err := r.state.Start(); err != nil {
  152. return err
  153. }
  154. }
  155. go r.processStateCh()
  156. go r.processDataCh()
  157. go r.processVoteCh()
  158. go r.processVoteSetBitsCh()
  159. go r.processPeerUpdates()
  160. return nil
  161. }
  162. // OnStop stops the reactor by signaling to all spawned goroutines to exit and
  163. // blocking until they all exit, as well as unsubscribing from events and stopping
  164. // state.
  165. func (r *Reactor) OnStop() {
  166. r.unsubscribeFromBroadcastEvents()
  167. if err := r.state.Stop(); err != nil {
  168. r.Logger.Error("failed to stop consensus state", "err", err)
  169. }
  170. if !r.WaitSync() {
  171. r.state.Wait()
  172. }
  173. r.mtx.Lock()
  174. peers := r.peers
  175. r.mtx.Unlock()
  176. // wait for all spawned peer goroutines to gracefully exit
  177. for _, ps := range peers {
  178. ps.closer.Close()
  179. }
  180. for _, ps := range peers {
  181. ps.broadcastWG.Wait()
  182. }
  183. // Close the StateChannel goroutine separately since it uses its own channel
  184. // to signal closure.
  185. close(r.stateCloseCh)
  186. <-r.stateCh.Done()
  187. // Close closeCh to signal to all spawned goroutines to gracefully exit. All
  188. // p2p Channels should execute Close().
  189. close(r.closeCh)
  190. // Wait for all p2p Channels to be closed before returning. This ensures we
  191. // can easily reason about synchronization of all p2p Channels and ensure no
  192. // panics will occur.
  193. <-r.voteSetBitsCh.Done()
  194. <-r.dataCh.Done()
  195. <-r.voteCh.Done()
  196. <-r.peerUpdates.Done()
  197. }
  198. // SetEventBus sets the reactor's event bus.
  199. func (r *Reactor) SetEventBus(b *types.EventBus) {
  200. r.eventBus = b
  201. r.state.SetEventBus(b)
  202. }
  203. // WaitSync returns whether the consensus reactor is waiting for state/fast sync.
  204. func (r *Reactor) WaitSync() bool {
  205. r.mtx.RLock()
  206. defer r.mtx.RUnlock()
  207. return r.waitSync
  208. }
  209. // ReactorMetrics sets the reactor's metrics as an option function.
  210. func ReactorMetrics(metrics *Metrics) ReactorOption {
  211. return func(r *Reactor) { r.Metrics = metrics }
  212. }
  213. // SwitchToConsensus switches from fast-sync mode to consensus mode. It resets
  214. // the state, turns off fast-sync, and starts the consensus state-machine.
  215. func (r *Reactor) SwitchToConsensus(state sm.State, skipWAL bool) {
  216. r.Logger.Info("switching to consensus")
  217. // we have no votes, so reconstruct LastCommit from SeenCommit
  218. if state.LastBlockHeight > 0 {
  219. r.state.reconstructLastCommit(state)
  220. }
  221. // NOTE: The line below causes broadcastNewRoundStepRoutine() to broadcast a
  222. // NewRoundStepMessage.
  223. r.state.updateToState(state)
  224. r.mtx.Lock()
  225. r.waitSync = false
  226. r.mtx.Unlock()
  227. r.Metrics.FastSyncing.Set(0)
  228. r.Metrics.StateSyncing.Set(0)
  229. if skipWAL {
  230. r.state.doWALCatchup = false
  231. }
  232. if err := r.state.Start(); err != nil {
  233. panic(fmt.Sprintf(`failed to start consensus state: %v
  234. conS:
  235. %+v
  236. conR:
  237. %+v`, err, r.state, r))
  238. }
  239. }
  240. // String returns a string representation of the Reactor.
  241. //
  242. // NOTE: For now, it is just a hard-coded string to avoid accessing unprotected
  243. // shared variables.
  244. //
  245. // TODO: improve!
  246. func (r *Reactor) String() string {
  247. return "ConsensusReactor"
  248. }
  249. // StringIndented returns an indented string representation of the Reactor.
  250. func (r *Reactor) StringIndented(indent string) string {
  251. r.mtx.RLock()
  252. defer r.mtx.RUnlock()
  253. s := "ConsensusReactor{\n"
  254. s += indent + " " + r.state.StringIndented(indent+" ") + "\n"
  255. for _, ps := range r.peers {
  256. s += indent + " " + ps.StringIndented(indent+" ") + "\n"
  257. }
  258. s += indent + "}"
  259. return s
  260. }
  261. // GetPeerState returns PeerState for a given NodeID.
  262. func (r *Reactor) GetPeerState(peerID p2p.NodeID) (*PeerState, bool) {
  263. r.mtx.RLock()
  264. defer r.mtx.RUnlock()
  265. ps, ok := r.peers[peerID]
  266. return ps, ok
  267. }
  268. func (r *Reactor) broadcastNewRoundStepMessage(rs *cstypes.RoundState) {
  269. r.stateCh.Out <- p2p.Envelope{
  270. Broadcast: true,
  271. Message: makeRoundStepMessage(rs),
  272. }
  273. }
  274. func (r *Reactor) broadcastNewValidBlockMessage(rs *cstypes.RoundState) {
  275. psHeader := rs.ProposalBlockParts.Header()
  276. r.stateCh.Out <- p2p.Envelope{
  277. Broadcast: true,
  278. Message: &tmcons.NewValidBlock{
  279. Height: rs.Height,
  280. Round: rs.Round,
  281. BlockPartSetHeader: psHeader.ToProto(),
  282. BlockParts: rs.ProposalBlockParts.BitArray().ToProto(),
  283. IsCommit: rs.Step == cstypes.RoundStepCommit,
  284. },
  285. }
  286. }
  287. func (r *Reactor) broadcastHasVoteMessage(vote *types.Vote) {
  288. r.stateCh.Out <- p2p.Envelope{
  289. Broadcast: true,
  290. Message: &tmcons.HasVote{
  291. Height: vote.Height,
  292. Round: vote.Round,
  293. Type: vote.Type,
  294. Index: vote.ValidatorIndex,
  295. },
  296. }
  297. }
  298. // subscribeToBroadcastEvents subscribes for new round steps and votes using the
  299. // internal pubsub defined in the consensus state to broadcast them to peers
  300. // upon receiving.
  301. func (r *Reactor) subscribeToBroadcastEvents() {
  302. err := r.state.evsw.AddListenerForEvent(
  303. listenerIDConsensus,
  304. types.EventNewRoundStep,
  305. func(data tmevents.EventData) {
  306. r.broadcastNewRoundStepMessage(data.(*cstypes.RoundState))
  307. },
  308. )
  309. if err != nil {
  310. r.Logger.Error("failed to add listener for events", "err", err)
  311. }
  312. err = r.state.evsw.AddListenerForEvent(
  313. listenerIDConsensus,
  314. types.EventValidBlock,
  315. func(data tmevents.EventData) {
  316. r.broadcastNewValidBlockMessage(data.(*cstypes.RoundState))
  317. },
  318. )
  319. if err != nil {
  320. r.Logger.Error("failed to add listener for events", "err", err)
  321. }
  322. err = r.state.evsw.AddListenerForEvent(
  323. listenerIDConsensus,
  324. types.EventVote,
  325. func(data tmevents.EventData) {
  326. r.broadcastHasVoteMessage(data.(*types.Vote))
  327. },
  328. )
  329. if err != nil {
  330. r.Logger.Error("failed to add listener for events", "err", err)
  331. }
  332. }
  333. func (r *Reactor) unsubscribeFromBroadcastEvents() {
  334. r.state.evsw.RemoveListener(listenerIDConsensus)
  335. }
  336. func makeRoundStepMessage(rs *cstypes.RoundState) *tmcons.NewRoundStep {
  337. return &tmcons.NewRoundStep{
  338. Height: rs.Height,
  339. Round: rs.Round,
  340. Step: uint32(rs.Step),
  341. SecondsSinceStartTime: int64(time.Since(rs.StartTime).Seconds()),
  342. LastCommitRound: rs.LastCommit.GetRound(),
  343. }
  344. }
  345. func (r *Reactor) sendNewRoundStepMessage(peerID p2p.NodeID) {
  346. rs := r.state.GetRoundState()
  347. msg := makeRoundStepMessage(rs)
  348. r.stateCh.Out <- p2p.Envelope{
  349. To: peerID,
  350. Message: msg,
  351. }
  352. }
  353. func (r *Reactor) gossipDataForCatchup(rs *cstypes.RoundState, prs *cstypes.PeerRoundState, ps *PeerState) {
  354. logger := r.Logger.With("height", prs.Height).With("peer", ps.peerID)
  355. if index, ok := prs.ProposalBlockParts.Not().PickRandom(); ok {
  356. // ensure that the peer's PartSetHeader is correct
  357. blockMeta := r.state.blockStore.LoadBlockMeta(prs.Height)
  358. if blockMeta == nil {
  359. logger.Error(
  360. "failed to load block meta",
  361. "our_height", rs.Height,
  362. "blockstore_base", r.state.blockStore.Base(),
  363. "blockstore_height", r.state.blockStore.Height(),
  364. )
  365. time.Sleep(r.state.config.PeerGossipSleepDuration)
  366. return
  367. } else if !blockMeta.BlockID.PartSetHeader.Equals(prs.ProposalBlockPartSetHeader) {
  368. logger.Info(
  369. "peer ProposalBlockPartSetHeader mismatch; sleeping",
  370. "block_part_set_header", blockMeta.BlockID.PartSetHeader,
  371. "peer_block_part_set_header", prs.ProposalBlockPartSetHeader,
  372. )
  373. time.Sleep(r.state.config.PeerGossipSleepDuration)
  374. return
  375. }
  376. part := r.state.blockStore.LoadBlockPart(prs.Height, index)
  377. if part == nil {
  378. logger.Error(
  379. "failed to load block part",
  380. "index", index,
  381. "block_part_set_header", blockMeta.BlockID.PartSetHeader,
  382. "peer_block_part_set_header", prs.ProposalBlockPartSetHeader,
  383. )
  384. time.Sleep(r.state.config.PeerGossipSleepDuration)
  385. return
  386. }
  387. partProto, err := part.ToProto()
  388. if err != nil {
  389. logger.Error("failed to convert block part to proto", "err", err)
  390. time.Sleep(r.state.config.PeerGossipSleepDuration)
  391. return
  392. }
  393. logger.Debug("sending block part for catchup", "round", prs.Round, "index", index)
  394. r.dataCh.Out <- p2p.Envelope{
  395. To: ps.peerID,
  396. Message: &tmcons.BlockPart{
  397. Height: prs.Height, // not our height, so it does not matter.
  398. Round: prs.Round, // not our height, so it does not matter
  399. Part: *partProto,
  400. },
  401. }
  402. return
  403. }
  404. time.Sleep(r.state.config.PeerGossipSleepDuration)
  405. }
  406. func (r *Reactor) gossipDataRoutine(ps *PeerState) {
  407. logger := r.Logger.With("peer", ps.peerID)
  408. defer ps.broadcastWG.Done()
  409. OUTER_LOOP:
  410. for {
  411. if !r.IsRunning() {
  412. return
  413. }
  414. select {
  415. case <-ps.closer.Done():
  416. // The peer is marked for removal via a PeerUpdate as the doneCh was
  417. // explicitly closed to signal we should exit.
  418. return
  419. default:
  420. }
  421. rs := r.state.GetRoundState()
  422. prs := ps.GetRoundState()
  423. // Send proposal Block parts?
  424. if rs.ProposalBlockParts.HasHeader(prs.ProposalBlockPartSetHeader) {
  425. if index, ok := rs.ProposalBlockParts.BitArray().Sub(prs.ProposalBlockParts.Copy()).PickRandom(); ok {
  426. part := rs.ProposalBlockParts.GetPart(index)
  427. partProto, err := part.ToProto()
  428. if err != nil {
  429. logger.Error("failed to convert block part to proto", "err", err)
  430. return
  431. }
  432. logger.Debug("sending block part", "height", prs.Height, "round", prs.Round)
  433. r.dataCh.Out <- p2p.Envelope{
  434. To: ps.peerID,
  435. Message: &tmcons.BlockPart{
  436. Height: rs.Height, // this tells peer that this part applies to us
  437. Round: rs.Round, // this tells peer that this part applies to us
  438. Part: *partProto,
  439. },
  440. }
  441. ps.SetHasProposalBlockPart(prs.Height, prs.Round, index)
  442. continue OUTER_LOOP
  443. }
  444. }
  445. // if the peer is on a previous height that we have, help catch up
  446. blockStoreBase := r.state.blockStore.Base()
  447. if blockStoreBase > 0 && 0 < prs.Height && prs.Height < rs.Height && prs.Height >= blockStoreBase {
  448. heightLogger := logger.With("height", prs.Height)
  449. // If we never received the commit message from the peer, the block parts
  450. // will not be initialized.
  451. if prs.ProposalBlockParts == nil {
  452. blockMeta := r.state.blockStore.LoadBlockMeta(prs.Height)
  453. if blockMeta == nil {
  454. heightLogger.Error(
  455. "failed to load block meta",
  456. "blockstoreBase", blockStoreBase,
  457. "blockstoreHeight", r.state.blockStore.Height(),
  458. )
  459. time.Sleep(r.state.config.PeerGossipSleepDuration)
  460. } else {
  461. ps.InitProposalBlockParts(blockMeta.BlockID.PartSetHeader)
  462. }
  463. // Continue the loop since prs is a copy and not effected by this
  464. // initialization.
  465. continue OUTER_LOOP
  466. }
  467. r.gossipDataForCatchup(rs, prs, ps)
  468. continue OUTER_LOOP
  469. }
  470. // if height and round don't match, sleep
  471. if (rs.Height != prs.Height) || (rs.Round != prs.Round) {
  472. time.Sleep(r.state.config.PeerGossipSleepDuration)
  473. continue OUTER_LOOP
  474. }
  475. // By here, height and round match.
  476. // Proposal block parts were already matched and sent if any were wanted.
  477. // (These can match on hash so the round doesn't matter)
  478. // Now consider sending other things, like the Proposal itself.
  479. // Send Proposal && ProposalPOL BitArray?
  480. if rs.Proposal != nil && !prs.Proposal {
  481. // Proposal: share the proposal metadata with peer.
  482. {
  483. propProto := rs.Proposal.ToProto()
  484. logger.Debug("sending proposal", "height", prs.Height, "round", prs.Round)
  485. r.dataCh.Out <- p2p.Envelope{
  486. To: ps.peerID,
  487. Message: &tmcons.Proposal{
  488. Proposal: *propProto,
  489. },
  490. }
  491. // NOTE: A peer might have received a different proposal message, so
  492. // this Proposal msg will be rejected!
  493. ps.SetHasProposal(rs.Proposal)
  494. }
  495. // ProposalPOL: lets peer know which POL votes we have so far. The peer
  496. // must receive ProposalMessage first. Note, rs.Proposal was validated,
  497. // so rs.Proposal.POLRound <= rs.Round, so we definitely have
  498. // rs.Votes.Prevotes(rs.Proposal.POLRound).
  499. if 0 <= rs.Proposal.POLRound {
  500. pPol := rs.Votes.Prevotes(rs.Proposal.POLRound).BitArray()
  501. pPolProto := pPol.ToProto()
  502. logger.Debug("sending POL", "height", prs.Height, "round", prs.Round)
  503. r.dataCh.Out <- p2p.Envelope{
  504. To: ps.peerID,
  505. Message: &tmcons.ProposalPOL{
  506. Height: rs.Height,
  507. ProposalPolRound: rs.Proposal.POLRound,
  508. ProposalPol: *pPolProto,
  509. },
  510. }
  511. }
  512. continue OUTER_LOOP
  513. }
  514. // nothing to do -- sleep
  515. time.Sleep(r.state.config.PeerGossipSleepDuration)
  516. continue OUTER_LOOP
  517. }
  518. }
  519. // pickSendVote picks a vote and sends it to the peer. It will return true if
  520. // there is a vote to send and false otherwise.
  521. func (r *Reactor) pickSendVote(ps *PeerState, votes types.VoteSetReader) bool {
  522. if vote, ok := ps.PickVoteToSend(votes); ok {
  523. r.Logger.Debug("sending vote message", "ps", ps, "vote", vote)
  524. r.voteCh.Out <- p2p.Envelope{
  525. To: ps.peerID,
  526. Message: &tmcons.Vote{
  527. Vote: vote.ToProto(),
  528. },
  529. }
  530. ps.SetHasVote(vote)
  531. return true
  532. }
  533. return false
  534. }
  535. func (r *Reactor) gossipVotesForHeight(rs *cstypes.RoundState, prs *cstypes.PeerRoundState, ps *PeerState) bool {
  536. logger := r.Logger.With("height", prs.Height).With("peer", ps.peerID)
  537. // if there are lastCommits to send...
  538. if prs.Step == cstypes.RoundStepNewHeight {
  539. if r.pickSendVote(ps, rs.LastCommit) {
  540. logger.Debug("picked rs.LastCommit to send")
  541. return true
  542. }
  543. }
  544. // if there are POL prevotes to send...
  545. if prs.Step <= cstypes.RoundStepPropose && prs.Round != -1 && prs.Round <= rs.Round && prs.ProposalPOLRound != -1 {
  546. if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
  547. if r.pickSendVote(ps, polPrevotes) {
  548. logger.Debug("picked rs.Prevotes(prs.ProposalPOLRound) to send", "round", prs.ProposalPOLRound)
  549. return true
  550. }
  551. }
  552. }
  553. // if there are prevotes to send...
  554. if prs.Step <= cstypes.RoundStepPrevoteWait && prs.Round != -1 && prs.Round <= rs.Round {
  555. if r.pickSendVote(ps, rs.Votes.Prevotes(prs.Round)) {
  556. logger.Debug("picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
  557. return true
  558. }
  559. }
  560. // if there are precommits to send...
  561. if prs.Step <= cstypes.RoundStepPrecommitWait && prs.Round != -1 && prs.Round <= rs.Round {
  562. if r.pickSendVote(ps, rs.Votes.Precommits(prs.Round)) {
  563. logger.Debug("picked rs.Precommits(prs.Round) to send", "round", prs.Round)
  564. return true
  565. }
  566. }
  567. // if there are prevotes to send...(which are needed because of validBlock mechanism)
  568. if prs.Round != -1 && prs.Round <= rs.Round {
  569. if r.pickSendVote(ps, rs.Votes.Prevotes(prs.Round)) {
  570. logger.Debug("picked rs.Prevotes(prs.Round) to send", "round", prs.Round)
  571. return true
  572. }
  573. }
  574. // if there are POLPrevotes to send...
  575. if prs.ProposalPOLRound != -1 {
  576. if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil {
  577. if r.pickSendVote(ps, polPrevotes) {
  578. logger.Debug("picked rs.Prevotes(prs.ProposalPOLRound) to send", "round", prs.ProposalPOLRound)
  579. return true
  580. }
  581. }
  582. }
  583. return false
  584. }
  585. func (r *Reactor) gossipVotesRoutine(ps *PeerState) {
  586. logger := r.Logger.With("peer", ps.peerID)
  587. defer ps.broadcastWG.Done()
  588. // XXX: simple hack to throttle logs upon sleep
  589. logThrottle := 0
  590. OUTER_LOOP:
  591. for {
  592. if !r.IsRunning() {
  593. return
  594. }
  595. select {
  596. case <-ps.closer.Done():
  597. // The peer is marked for removal via a PeerUpdate as the doneCh was
  598. // explicitly closed to signal we should exit.
  599. return
  600. default:
  601. }
  602. rs := r.state.GetRoundState()
  603. prs := ps.GetRoundState()
  604. switch logThrottle {
  605. case 1: // first sleep
  606. logThrottle = 2
  607. case 2: // no more sleep
  608. logThrottle = 0
  609. }
  610. // if height matches, then send LastCommit, Prevotes, and Precommits
  611. if rs.Height == prs.Height {
  612. if r.gossipVotesForHeight(rs, prs, ps) {
  613. continue OUTER_LOOP
  614. }
  615. }
  616. // special catchup logic -- if peer is lagging by height 1, send LastCommit
  617. if prs.Height != 0 && rs.Height == prs.Height+1 {
  618. if r.pickSendVote(ps, rs.LastCommit) {
  619. logger.Debug("picked rs.LastCommit to send", "height", prs.Height)
  620. continue OUTER_LOOP
  621. }
  622. }
  623. // catchup logic -- if peer is lagging by more than 1, send Commit
  624. blockStoreBase := r.state.blockStore.Base()
  625. if blockStoreBase > 0 && prs.Height != 0 && rs.Height >= prs.Height+2 && prs.Height >= blockStoreBase {
  626. // Load the block commit for prs.Height, which contains precommit
  627. // signatures for prs.Height.
  628. if commit := r.state.blockStore.LoadBlockCommit(prs.Height); commit != nil {
  629. if r.pickSendVote(ps, commit) {
  630. logger.Debug("picked Catchup commit to send", "height", prs.Height)
  631. continue OUTER_LOOP
  632. }
  633. }
  634. }
  635. if logThrottle == 0 {
  636. // we sent nothing -- sleep
  637. logThrottle = 1
  638. logger.Debug(
  639. "no votes to send; sleeping",
  640. "rs.Height", rs.Height,
  641. "prs.Height", prs.Height,
  642. "localPV", rs.Votes.Prevotes(rs.Round).BitArray(), "peerPV", prs.Prevotes,
  643. "localPC", rs.Votes.Precommits(rs.Round).BitArray(), "peerPC", prs.Precommits,
  644. )
  645. } else if logThrottle == 2 {
  646. logThrottle = 1
  647. }
  648. time.Sleep(r.state.config.PeerGossipSleepDuration)
  649. continue OUTER_LOOP
  650. }
  651. }
  652. // NOTE: `queryMaj23Routine` has a simple crude design since it only comes
  653. // into play for liveness when there's a signature DDoS attack happening.
  654. func (r *Reactor) queryMaj23Routine(ps *PeerState) {
  655. defer ps.broadcastWG.Done()
  656. OUTER_LOOP:
  657. for {
  658. if !r.IsRunning() {
  659. return
  660. }
  661. select {
  662. case <-ps.closer.Done():
  663. // The peer is marked for removal via a PeerUpdate as the doneCh was
  664. // explicitly closed to signal we should exit.
  665. return
  666. default:
  667. }
  668. // maybe send Height/Round/Prevotes
  669. {
  670. rs := r.state.GetRoundState()
  671. prs := ps.GetRoundState()
  672. if rs.Height == prs.Height {
  673. if maj23, ok := rs.Votes.Prevotes(prs.Round).TwoThirdsMajority(); ok {
  674. r.stateCh.Out <- p2p.Envelope{
  675. To: ps.peerID,
  676. Message: &tmcons.VoteSetMaj23{
  677. Height: prs.Height,
  678. Round: prs.Round,
  679. Type: tmproto.PrevoteType,
  680. BlockID: maj23.ToProto(),
  681. },
  682. }
  683. time.Sleep(r.state.config.PeerQueryMaj23SleepDuration)
  684. }
  685. }
  686. }
  687. // maybe send Height/Round/Precommits
  688. {
  689. rs := r.state.GetRoundState()
  690. prs := ps.GetRoundState()
  691. if rs.Height == prs.Height {
  692. if maj23, ok := rs.Votes.Precommits(prs.Round).TwoThirdsMajority(); ok {
  693. r.stateCh.Out <- p2p.Envelope{
  694. To: ps.peerID,
  695. Message: &tmcons.VoteSetMaj23{
  696. Height: prs.Height,
  697. Round: prs.Round,
  698. Type: tmproto.PrecommitType,
  699. BlockID: maj23.ToProto(),
  700. },
  701. }
  702. time.Sleep(r.state.config.PeerQueryMaj23SleepDuration)
  703. }
  704. }
  705. }
  706. // maybe send Height/Round/ProposalPOL
  707. {
  708. rs := r.state.GetRoundState()
  709. prs := ps.GetRoundState()
  710. if rs.Height == prs.Height && prs.ProposalPOLRound >= 0 {
  711. if maj23, ok := rs.Votes.Prevotes(prs.ProposalPOLRound).TwoThirdsMajority(); ok {
  712. r.stateCh.Out <- p2p.Envelope{
  713. To: ps.peerID,
  714. Message: &tmcons.VoteSetMaj23{
  715. Height: prs.Height,
  716. Round: prs.ProposalPOLRound,
  717. Type: tmproto.PrevoteType,
  718. BlockID: maj23.ToProto(),
  719. },
  720. }
  721. time.Sleep(r.state.config.PeerQueryMaj23SleepDuration)
  722. }
  723. }
  724. }
  725. // Little point sending LastCommitRound/LastCommit, these are fleeting and
  726. // non-blocking.
  727. // maybe send Height/CatchupCommitRound/CatchupCommit
  728. {
  729. prs := ps.GetRoundState()
  730. if prs.CatchupCommitRound != -1 && prs.Height > 0 && prs.Height <= r.state.blockStore.Height() &&
  731. prs.Height >= r.state.blockStore.Base() {
  732. if commit := r.state.LoadCommit(prs.Height); commit != nil {
  733. r.stateCh.Out <- p2p.Envelope{
  734. To: ps.peerID,
  735. Message: &tmcons.VoteSetMaj23{
  736. Height: prs.Height,
  737. Round: commit.Round,
  738. Type: tmproto.PrecommitType,
  739. BlockID: commit.BlockID.ToProto(),
  740. },
  741. }
  742. time.Sleep(r.state.config.PeerQueryMaj23SleepDuration)
  743. }
  744. }
  745. }
  746. time.Sleep(r.state.config.PeerQueryMaj23SleepDuration)
  747. continue OUTER_LOOP
  748. }
  749. }
  750. // processPeerUpdate process a peer update message. For new or reconnected peers,
  751. // we create a peer state if one does not exist for the peer, which should always
  752. // be the case, and we spawn all the relevant goroutine to broadcast messages to
  753. // the peer. During peer removal, we remove the peer for our set of peers and
  754. // signal to all spawned goroutines to gracefully exit in a non-blocking manner.
  755. func (r *Reactor) processPeerUpdate(peerUpdate p2p.PeerUpdate) {
  756. r.Logger.Debug("received peer update", "peer", peerUpdate.NodeID, "status", peerUpdate.Status)
  757. r.mtx.Lock()
  758. defer r.mtx.Unlock()
  759. switch peerUpdate.Status {
  760. case p2p.PeerStatusUp:
  761. // Do not allow starting new broadcasting goroutines after reactor shutdown
  762. // has been initiated. This can happen after we've manually closed all
  763. // peer goroutines and closed r.closeCh, but the router still sends in-flight
  764. // peer updates.
  765. if !r.IsRunning() {
  766. return
  767. }
  768. var (
  769. ps *PeerState
  770. ok bool
  771. )
  772. ps, ok = r.peers[peerUpdate.NodeID]
  773. if !ok {
  774. ps = NewPeerState(r.Logger, peerUpdate.NodeID)
  775. r.peers[peerUpdate.NodeID] = ps
  776. }
  777. if !ps.IsRunning() {
  778. // Set the peer state's closer to signal to all spawned goroutines to exit
  779. // when the peer is removed. We also set the running state to ensure we
  780. // do not spawn multiple instances of the same goroutines and finally we
  781. // set the waitgroup counter so we know when all goroutines have exited.
  782. ps.broadcastWG.Add(3)
  783. ps.SetRunning(true)
  784. // start goroutines for this peer
  785. go r.gossipDataRoutine(ps)
  786. go r.gossipVotesRoutine(ps)
  787. go r.queryMaj23Routine(ps)
  788. // Send our state to the peer. If we're fast-syncing, broadcast a
  789. // RoundStepMessage later upon SwitchToConsensus().
  790. if !r.waitSync {
  791. go r.sendNewRoundStepMessage(ps.peerID)
  792. }
  793. }
  794. case p2p.PeerStatusDown:
  795. ps, ok := r.peers[peerUpdate.NodeID]
  796. if ok && ps.IsRunning() {
  797. // signal to all spawned goroutines for the peer to gracefully exit
  798. ps.closer.Close()
  799. go func() {
  800. // Wait for all spawned broadcast goroutines to exit before marking the
  801. // peer state as no longer running and removal from the peers map.
  802. ps.broadcastWG.Wait()
  803. r.mtx.Lock()
  804. delete(r.peers, peerUpdate.NodeID)
  805. r.mtx.Unlock()
  806. ps.SetRunning(false)
  807. }()
  808. }
  809. }
  810. }
  811. // handleStateMessage handles envelopes sent from peers on the StateChannel.
  812. // An error is returned if the message is unrecognized or if validation fails.
  813. // If we fail to find the peer state for the envelope sender, we perform a no-op
  814. // and return. This can happen when we process the envelope after the peer is
  815. // removed.
  816. func (r *Reactor) handleStateMessage(envelope p2p.Envelope, msgI Message) error {
  817. ps, ok := r.GetPeerState(envelope.From)
  818. if !ok || ps == nil {
  819. r.Logger.Debug("failed to find peer state", "peer", envelope.From, "ch_id", "StateChannel")
  820. return nil
  821. }
  822. switch msg := envelope.Message.(type) {
  823. case *tmcons.NewRoundStep:
  824. r.state.mtx.RLock()
  825. initialHeight := r.state.state.InitialHeight
  826. r.state.mtx.RUnlock()
  827. if err := msgI.(*NewRoundStepMessage).ValidateHeight(initialHeight); err != nil {
  828. r.Logger.Error("peer sent us an invalid msg", "msg", msg, "err", err)
  829. return err
  830. }
  831. ps.ApplyNewRoundStepMessage(msgI.(*NewRoundStepMessage))
  832. case *tmcons.NewValidBlock:
  833. ps.ApplyNewValidBlockMessage(msgI.(*NewValidBlockMessage))
  834. case *tmcons.HasVote:
  835. ps.ApplyHasVoteMessage(msgI.(*HasVoteMessage))
  836. case *tmcons.VoteSetMaj23:
  837. r.state.mtx.RLock()
  838. height, votes := r.state.Height, r.state.Votes
  839. r.state.mtx.RUnlock()
  840. if height != msg.Height {
  841. return nil
  842. }
  843. vsmMsg := msgI.(*VoteSetMaj23Message)
  844. // peer claims to have a maj23 for some BlockID at <H,R,S>
  845. err := votes.SetPeerMaj23(msg.Round, msg.Type, ps.peerID, vsmMsg.BlockID)
  846. if err != nil {
  847. return err
  848. }
  849. // Respond with a VoteSetBitsMessage showing which votes we have and
  850. // consequently shows which we don't have.
  851. var ourVotes *bits.BitArray
  852. switch vsmMsg.Type {
  853. case tmproto.PrevoteType:
  854. ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(vsmMsg.BlockID)
  855. case tmproto.PrecommitType:
  856. ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(vsmMsg.BlockID)
  857. default:
  858. panic("bad VoteSetBitsMessage field type; forgot to add a check in ValidateBasic?")
  859. }
  860. eMsg := &tmcons.VoteSetBits{
  861. Height: msg.Height,
  862. Round: msg.Round,
  863. Type: msg.Type,
  864. BlockID: msg.BlockID,
  865. }
  866. if votesProto := ourVotes.ToProto(); votesProto != nil {
  867. eMsg.Votes = *votesProto
  868. }
  869. r.voteSetBitsCh.Out <- p2p.Envelope{
  870. To: envelope.From,
  871. Message: eMsg,
  872. }
  873. default:
  874. return fmt.Errorf("received unknown message on StateChannel: %T", msg)
  875. }
  876. return nil
  877. }
  878. // handleDataMessage handles envelopes sent from peers on the DataChannel. If we
  879. // fail to find the peer state for the envelope sender, we perform a no-op and
  880. // return. This can happen when we process the envelope after the peer is
  881. // removed.
  882. func (r *Reactor) handleDataMessage(envelope p2p.Envelope, msgI Message) error {
  883. logger := r.Logger.With("peer", envelope.From, "ch_id", "DataChannel")
  884. ps, ok := r.GetPeerState(envelope.From)
  885. if !ok || ps == nil {
  886. r.Logger.Debug("failed to find peer state")
  887. return nil
  888. }
  889. if r.WaitSync() {
  890. logger.Info("ignoring message received during sync", "msg", msgI)
  891. return nil
  892. }
  893. switch msg := envelope.Message.(type) {
  894. case *tmcons.Proposal:
  895. pMsg := msgI.(*ProposalMessage)
  896. ps.SetHasProposal(pMsg.Proposal)
  897. r.state.peerMsgQueue <- msgInfo{pMsg, envelope.From}
  898. case *tmcons.ProposalPOL:
  899. ps.ApplyProposalPOLMessage(msgI.(*ProposalPOLMessage))
  900. case *tmcons.BlockPart:
  901. bpMsg := msgI.(*BlockPartMessage)
  902. ps.SetHasProposalBlockPart(bpMsg.Height, bpMsg.Round, int(bpMsg.Part.Index))
  903. r.Metrics.BlockParts.With("peer_id", string(envelope.From)).Add(1)
  904. r.state.peerMsgQueue <- msgInfo{bpMsg, envelope.From}
  905. default:
  906. return fmt.Errorf("received unknown message on DataChannel: %T", msg)
  907. }
  908. return nil
  909. }
  910. // handleVoteMessage handles envelopes sent from peers on the VoteChannel. If we
  911. // fail to find the peer state for the envelope sender, we perform a no-op and
  912. // return. This can happen when we process the envelope after the peer is
  913. // removed.
  914. func (r *Reactor) handleVoteMessage(envelope p2p.Envelope, msgI Message) error {
  915. logger := r.Logger.With("peer", envelope.From, "ch_id", "VoteChannel")
  916. ps, ok := r.GetPeerState(envelope.From)
  917. if !ok || ps == nil {
  918. r.Logger.Debug("failed to find peer state")
  919. return nil
  920. }
  921. if r.WaitSync() {
  922. logger.Info("ignoring message received during sync", "msg", msgI)
  923. return nil
  924. }
  925. switch msg := envelope.Message.(type) {
  926. case *tmcons.Vote:
  927. r.state.mtx.RLock()
  928. height, valSize, lastCommitSize := r.state.Height, r.state.Validators.Size(), r.state.LastCommit.Size()
  929. r.state.mtx.RUnlock()
  930. vMsg := msgI.(*VoteMessage)
  931. ps.EnsureVoteBitArrays(height, valSize)
  932. ps.EnsureVoteBitArrays(height-1, lastCommitSize)
  933. ps.SetHasVote(vMsg.Vote)
  934. r.state.peerMsgQueue <- msgInfo{vMsg, envelope.From}
  935. default:
  936. return fmt.Errorf("received unknown message on VoteChannel: %T", msg)
  937. }
  938. return nil
  939. }
  940. // handleVoteSetBitsMessage handles envelopes sent from peers on the
  941. // VoteSetBitsChannel. If we fail to find the peer state for the envelope sender,
  942. // we perform a no-op and return. This can happen when we process the envelope
  943. // after the peer is removed.
  944. func (r *Reactor) handleVoteSetBitsMessage(envelope p2p.Envelope, msgI Message) error {
  945. logger := r.Logger.With("peer", envelope.From, "ch_id", "VoteSetBitsChannel")
  946. ps, ok := r.GetPeerState(envelope.From)
  947. if !ok || ps == nil {
  948. r.Logger.Debug("failed to find peer state")
  949. return nil
  950. }
  951. if r.WaitSync() {
  952. logger.Info("ignoring message received during sync", "msg", msgI)
  953. return nil
  954. }
  955. switch msg := envelope.Message.(type) {
  956. case *tmcons.VoteSetBits:
  957. r.state.mtx.RLock()
  958. height, votes := r.state.Height, r.state.Votes
  959. r.state.mtx.RUnlock()
  960. vsbMsg := msgI.(*VoteSetBitsMessage)
  961. if height == msg.Height {
  962. var ourVotes *bits.BitArray
  963. switch msg.Type {
  964. case tmproto.PrevoteType:
  965. ourVotes = votes.Prevotes(msg.Round).BitArrayByBlockID(vsbMsg.BlockID)
  966. case tmproto.PrecommitType:
  967. ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(vsbMsg.BlockID)
  968. default:
  969. panic("bad VoteSetBitsMessage field type; forgot to add a check in ValidateBasic?")
  970. }
  971. ps.ApplyVoteSetBitsMessage(vsbMsg, ourVotes)
  972. } else {
  973. ps.ApplyVoteSetBitsMessage(vsbMsg, nil)
  974. }
  975. default:
  976. return fmt.Errorf("received unknown message on VoteSetBitsChannel: %T", msg)
  977. }
  978. return nil
  979. }
  980. // handleMessage handles an Envelope sent from a peer on a specific p2p Channel.
  981. // It will handle errors and any possible panics gracefully. A caller can handle
  982. // any error returned by sending a PeerError on the respective channel.
  983. //
  984. // NOTE: We process these messages even when we're fast_syncing. Messages affect
  985. // either a peer state or the consensus state. Peer state updates can happen in
  986. // parallel, but processing of proposals, block parts, and votes are ordered by
  987. // the p2p channel.
  988. //
  989. // NOTE: We block on consensus state for proposals, block parts, and votes.
  990. func (r *Reactor) handleMessage(chID p2p.ChannelID, envelope p2p.Envelope) (err error) {
  991. defer func() {
  992. if e := recover(); e != nil {
  993. err = fmt.Errorf("panic in processing message: %v", e)
  994. r.Logger.Error("recovering from processing message panic", "err", err)
  995. }
  996. }()
  997. // We wrap the envelope's message in a Proto wire type so we can convert back
  998. // the domain type that individual channel message handlers can work with. We
  999. // do this here once to avoid having to do it for each individual message type.
  1000. // and because a large part of the core business logic depends on these
  1001. // domain types opposed to simply working with the Proto types.
  1002. protoMsg := new(tmcons.Message)
  1003. if err := protoMsg.Wrap(envelope.Message); err != nil {
  1004. return err
  1005. }
  1006. msgI, err := MsgFromProto(protoMsg)
  1007. if err != nil {
  1008. return err
  1009. }
  1010. r.Logger.Debug("received message", "ch_id", chID, "message", msgI, "peer", envelope.From)
  1011. switch chID {
  1012. case StateChannel:
  1013. err = r.handleStateMessage(envelope, msgI)
  1014. case DataChannel:
  1015. err = r.handleDataMessage(envelope, msgI)
  1016. case VoteChannel:
  1017. err = r.handleVoteMessage(envelope, msgI)
  1018. case VoteSetBitsChannel:
  1019. err = r.handleVoteSetBitsMessage(envelope, msgI)
  1020. default:
  1021. err = fmt.Errorf("unknown channel ID (%d) for envelope (%v)", chID, envelope)
  1022. }
  1023. return err
  1024. }
  1025. // processStateCh initiates a blocking process where we listen for and handle
  1026. // envelopes on the StateChannel. Any error encountered during message
  1027. // execution will result in a PeerError being sent on the StateChannel. When
  1028. // the reactor is stopped, we will catch the signal and close the p2p Channel
  1029. // gracefully.
  1030. func (r *Reactor) processStateCh() {
  1031. defer r.stateCh.Close()
  1032. for {
  1033. select {
  1034. case envelope := <-r.stateCh.In:
  1035. if err := r.handleMessage(r.stateCh.ID, envelope); err != nil {
  1036. r.Logger.Error("failed to process message", "ch_id", r.stateCh.ID, "envelope", envelope, "err", err)
  1037. r.stateCh.Error <- p2p.PeerError{
  1038. NodeID: envelope.From,
  1039. Err: err,
  1040. }
  1041. }
  1042. case <-r.stateCloseCh:
  1043. r.Logger.Debug("stopped listening on StateChannel; closing...")
  1044. return
  1045. }
  1046. }
  1047. }
  1048. // processDataCh initiates a blocking process where we listen for and handle
  1049. // envelopes on the DataChannel. Any error encountered during message
  1050. // execution will result in a PeerError being sent on the DataChannel. When
  1051. // the reactor is stopped, we will catch the signal and close the p2p Channel
  1052. // gracefully.
  1053. func (r *Reactor) processDataCh() {
  1054. defer r.dataCh.Close()
  1055. for {
  1056. select {
  1057. case envelope := <-r.dataCh.In:
  1058. if err := r.handleMessage(r.dataCh.ID, envelope); err != nil {
  1059. r.Logger.Error("failed to process message", "ch_id", r.dataCh.ID, "envelope", envelope, "err", err)
  1060. r.dataCh.Error <- p2p.PeerError{
  1061. NodeID: envelope.From,
  1062. Err: err,
  1063. }
  1064. }
  1065. case <-r.closeCh:
  1066. r.Logger.Debug("stopped listening on DataChannel; closing...")
  1067. return
  1068. }
  1069. }
  1070. }
  1071. // processVoteCh initiates a blocking process where we listen for and handle
  1072. // envelopes on the VoteChannel. Any error encountered during message
  1073. // execution will result in a PeerError being sent on the VoteChannel. When
  1074. // the reactor is stopped, we will catch the signal and close the p2p Channel
  1075. // gracefully.
  1076. func (r *Reactor) processVoteCh() {
  1077. defer r.voteCh.Close()
  1078. for {
  1079. select {
  1080. case envelope := <-r.voteCh.In:
  1081. if err := r.handleMessage(r.voteCh.ID, envelope); err != nil {
  1082. r.Logger.Error("failed to process message", "ch_id", r.voteCh.ID, "envelope", envelope, "err", err)
  1083. r.voteCh.Error <- p2p.PeerError{
  1084. NodeID: envelope.From,
  1085. Err: err,
  1086. }
  1087. }
  1088. case <-r.closeCh:
  1089. r.Logger.Debug("stopped listening on VoteChannel; closing...")
  1090. return
  1091. }
  1092. }
  1093. }
  1094. // processVoteCh initiates a blocking process where we listen for and handle
  1095. // envelopes on the VoteSetBitsChannel. Any error encountered during message
  1096. // execution will result in a PeerError being sent on the VoteSetBitsChannel.
  1097. // When the reactor is stopped, we will catch the signal and close the p2p
  1098. // Channel gracefully.
  1099. func (r *Reactor) processVoteSetBitsCh() {
  1100. defer r.voteSetBitsCh.Close()
  1101. for {
  1102. select {
  1103. case envelope := <-r.voteSetBitsCh.In:
  1104. if err := r.handleMessage(r.voteSetBitsCh.ID, envelope); err != nil {
  1105. r.Logger.Error("failed to process message", "ch_id", r.voteSetBitsCh.ID, "envelope", envelope, "err", err)
  1106. r.voteSetBitsCh.Error <- p2p.PeerError{
  1107. NodeID: envelope.From,
  1108. Err: err,
  1109. }
  1110. }
  1111. case <-r.closeCh:
  1112. r.Logger.Debug("stopped listening on VoteSetBitsChannel; closing...")
  1113. return
  1114. }
  1115. }
  1116. }
  1117. // processPeerUpdates initiates a blocking process where we listen for and handle
  1118. // PeerUpdate messages. When the reactor is stopped, we will catch the signal and
  1119. // close the p2p PeerUpdatesCh gracefully.
  1120. func (r *Reactor) processPeerUpdates() {
  1121. defer r.peerUpdates.Close()
  1122. for {
  1123. select {
  1124. case peerUpdate := <-r.peerUpdates.Updates():
  1125. r.processPeerUpdate(peerUpdate)
  1126. case <-r.closeCh:
  1127. r.Logger.Debug("stopped listening on peer updates channel; closing...")
  1128. return
  1129. }
  1130. }
  1131. }
  1132. func (r *Reactor) peerStatsRoutine() {
  1133. for {
  1134. if !r.IsRunning() {
  1135. r.Logger.Info("stopping peerStatsRoutine")
  1136. return
  1137. }
  1138. select {
  1139. case msg := <-r.state.statsMsgQueue:
  1140. ps, ok := r.GetPeerState(msg.PeerID)
  1141. if !ok || ps == nil {
  1142. r.Logger.Debug("attempt to update stats for non-existent peer", "peer", msg.PeerID)
  1143. continue
  1144. }
  1145. switch msg.Msg.(type) {
  1146. case *VoteMessage:
  1147. if numVotes := ps.RecordVote(); numVotes%votesToContributeToBecomeGoodPeer == 0 { // nolint: staticcheck
  1148. // TODO: Handle peer quality via the peer manager.
  1149. // r.Switch.MarkPeerAsGood(peer)
  1150. }
  1151. case *BlockPartMessage:
  1152. if numParts := ps.RecordBlockPart(); numParts%blocksToContributeToBecomeGoodPeer == 0 { // nolint: staticcheck
  1153. // TODO: Handle peer quality via the peer manager.
  1154. // r.Switch.MarkPeerAsGood(peer)
  1155. }
  1156. }
  1157. case <-r.closeCh:
  1158. return
  1159. }
  1160. }
  1161. }