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.

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