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.

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