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.

1508 lines
42 KiB

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