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.

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