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.

845 lines
22 KiB

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
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
p2p: fix infinite loop in addrbook (#3232) * failing test * fix infinite loop in addrbook There are cases where we only have a small number of addresses marked good ("old"), but the selection mechanism keeps trying to select more of these addresses, and hence ends up in an infinite loop. Here we fix this to only try and select such "old" addresses if we have enough of them. Note this means, if we don't have enough of them, we may return more "new" addresses than otherwise expected by the newSelectionBias. This whole GetSelectionWithBias method probably needs to be rewritten, but this is a quick fix for the issue. * changelog * fix infinite loop if not enough new addrs * fix another potential infinite loop if a.nNew == 0 -> pickFromOldBucket=true, but we don't have enough items (a.nOld > len(oldBucketToAddrsMap) false) * Revert "fix another potential infinite loop" This reverts commit 146540c1125597162bd89820d611f6531f5e5e4b. * check num addresses instead of buckets, new test * fixed the int division * add slack to bias % in test, lint fixes * Added checks for selection content in test * test cleanup * Apply suggestions from code review Co-Authored-By: ebuchman <ethan@coinculture.info> * address review comments * change after Anton's review comments * use the same docker image we use for testing when building a binary for localnet * switch back to circleci classic * more review comments * more review comments * refactor addrbook_test * build linux binary inside docker in attempt to fix ``` --> Running dep + make build-linux GOOS=linux GOARCH=amd64 make build make[1]: Entering directory `/home/circleci/.go_workspace/src/github.com/tendermint/tendermint' CGO_ENABLED=0 go build -ldflags "-X github.com/tendermint/tendermint/version.GitCommit=`git rev-parse --short=8 HEAD`" -tags 'tendermint' -o build/tendermint ./cmd/tendermint/ p2p/pex/addrbook.go:373:13: undefined: math.Round ``` * change dir from /usr to /go * use concrete Go version for localnet binary * check for nil addresses just to be sure
6 years ago
p2p: fix infinite loop in addrbook (#3232) * failing test * fix infinite loop in addrbook There are cases where we only have a small number of addresses marked good ("old"), but the selection mechanism keeps trying to select more of these addresses, and hence ends up in an infinite loop. Here we fix this to only try and select such "old" addresses if we have enough of them. Note this means, if we don't have enough of them, we may return more "new" addresses than otherwise expected by the newSelectionBias. This whole GetSelectionWithBias method probably needs to be rewritten, but this is a quick fix for the issue. * changelog * fix infinite loop if not enough new addrs * fix another potential infinite loop if a.nNew == 0 -> pickFromOldBucket=true, but we don't have enough items (a.nOld > len(oldBucketToAddrsMap) false) * Revert "fix another potential infinite loop" This reverts commit 146540c1125597162bd89820d611f6531f5e5e4b. * check num addresses instead of buckets, new test * fixed the int division * add slack to bias % in test, lint fixes * Added checks for selection content in test * test cleanup * Apply suggestions from code review Co-Authored-By: ebuchman <ethan@coinculture.info> * address review comments * change after Anton's review comments * use the same docker image we use for testing when building a binary for localnet * switch back to circleci classic * more review comments * more review comments * refactor addrbook_test * build linux binary inside docker in attempt to fix ``` --> Running dep + make build-linux GOOS=linux GOARCH=amd64 make build make[1]: Entering directory `/home/circleci/.go_workspace/src/github.com/tendermint/tendermint' CGO_ENABLED=0 go build -ldflags "-X github.com/tendermint/tendermint/version.GitCommit=`git rev-parse --short=8 HEAD`" -tags 'tendermint' -o build/tendermint ./cmd/tendermint/ p2p/pex/addrbook.go:373:13: undefined: math.Round ``` * change dir from /usr to /go * use concrete Go version for localnet binary * check for nil addresses just to be sure
6 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
  1. // Modified for Tendermint
  2. // Originally Copyright (c) 2013-2014 Conformal Systems LLC.
  3. // https://github.com/conformal/btcd/blob/master/LICENSE
  4. package pex
  5. import (
  6. "crypto/sha256"
  7. "encoding/binary"
  8. "fmt"
  9. "math"
  10. "math/rand"
  11. "net"
  12. "sync"
  13. "time"
  14. "github.com/tendermint/tendermint/crypto"
  15. cmn "github.com/tendermint/tendermint/libs/common"
  16. "github.com/tendermint/tendermint/p2p"
  17. )
  18. const (
  19. bucketTypeNew = 0x01
  20. bucketTypeOld = 0x02
  21. )
  22. // AddrBook is an address book used for tracking peers
  23. // so we can gossip about them to others and select
  24. // peers to dial.
  25. // TODO: break this up?
  26. type AddrBook interface {
  27. cmn.Service
  28. // Add our own addresses so we don't later add ourselves
  29. AddOurAddress(*p2p.NetAddress)
  30. // Check if it is our address
  31. OurAddress(*p2p.NetAddress) bool
  32. AddPrivateIDs([]string)
  33. // Add and remove an address
  34. AddAddress(addr *p2p.NetAddress, src *p2p.NetAddress) error
  35. RemoveAddress(*p2p.NetAddress)
  36. // Check if the address is in the book
  37. HasAddress(*p2p.NetAddress) bool
  38. // Do we need more peers?
  39. NeedMoreAddrs() bool
  40. // Is Address Book Empty? Answer should not depend on being in your own
  41. // address book, or private peers
  42. Empty() bool
  43. // Pick an address to dial
  44. PickAddress(biasTowardsNewAddrs int) *p2p.NetAddress
  45. // Mark address
  46. MarkGood(*p2p.NetAddress)
  47. MarkAttempt(*p2p.NetAddress)
  48. MarkBad(*p2p.NetAddress)
  49. IsGood(*p2p.NetAddress) bool
  50. // Send a selection of addresses to peers
  51. GetSelection() []*p2p.NetAddress
  52. // Send a selection of addresses with bias
  53. GetSelectionWithBias(biasTowardsNewAddrs int) []*p2p.NetAddress
  54. // TODO: remove
  55. ListOfKnownAddresses() []*knownAddress
  56. // Persist to disk
  57. Save()
  58. }
  59. var _ AddrBook = (*addrBook)(nil)
  60. // addrBook - concurrency safe peer address manager.
  61. // Implements AddrBook.
  62. type addrBook struct {
  63. cmn.BaseService
  64. // immutable after creation
  65. filePath string
  66. routabilityStrict bool
  67. key string // random prefix for bucket placement
  68. // accessed concurrently
  69. mtx sync.Mutex
  70. rand *cmn.Rand
  71. ourAddrs map[string]struct{}
  72. privateIDs map[p2p.ID]struct{}
  73. addrLookup map[p2p.ID]*knownAddress // new & old
  74. bucketsOld []map[string]*knownAddress
  75. bucketsNew []map[string]*knownAddress
  76. nOld int
  77. nNew int
  78. wg sync.WaitGroup
  79. }
  80. // NewAddrBook creates a new address book.
  81. // Use Start to begin processing asynchronous address updates.
  82. func NewAddrBook(filePath string, routabilityStrict bool) *addrBook {
  83. am := &addrBook{
  84. rand: cmn.NewRand(),
  85. ourAddrs: make(map[string]struct{}),
  86. privateIDs: make(map[p2p.ID]struct{}),
  87. addrLookup: make(map[p2p.ID]*knownAddress),
  88. filePath: filePath,
  89. routabilityStrict: routabilityStrict,
  90. }
  91. am.init()
  92. am.BaseService = *cmn.NewBaseService(nil, "AddrBook", am)
  93. return am
  94. }
  95. // Initialize the buckets.
  96. // When modifying this, don't forget to update loadFromFile()
  97. func (a *addrBook) init() {
  98. a.key = crypto.CRandHex(24) // 24/2 * 8 = 96 bits
  99. // New addr buckets
  100. a.bucketsNew = make([]map[string]*knownAddress, newBucketCount)
  101. for i := range a.bucketsNew {
  102. a.bucketsNew[i] = make(map[string]*knownAddress)
  103. }
  104. // Old addr buckets
  105. a.bucketsOld = make([]map[string]*knownAddress, oldBucketCount)
  106. for i := range a.bucketsOld {
  107. a.bucketsOld[i] = make(map[string]*knownAddress)
  108. }
  109. }
  110. // OnStart implements Service.
  111. func (a *addrBook) OnStart() error {
  112. if err := a.BaseService.OnStart(); err != nil {
  113. return err
  114. }
  115. a.loadFromFile(a.filePath)
  116. // wg.Add to ensure that any invocation of .Wait()
  117. // later on will wait for saveRoutine to terminate.
  118. a.wg.Add(1)
  119. go a.saveRoutine()
  120. return nil
  121. }
  122. // OnStop implements Service.
  123. func (a *addrBook) OnStop() {
  124. a.BaseService.OnStop()
  125. }
  126. func (a *addrBook) Wait() {
  127. a.wg.Wait()
  128. }
  129. func (a *addrBook) FilePath() string {
  130. return a.filePath
  131. }
  132. //-------------------------------------------------------
  133. // AddOurAddress one of our addresses.
  134. func (a *addrBook) AddOurAddress(addr *p2p.NetAddress) {
  135. a.mtx.Lock()
  136. defer a.mtx.Unlock()
  137. a.Logger.Info("Add our address to book", "addr", addr)
  138. a.ourAddrs[addr.String()] = struct{}{}
  139. }
  140. // OurAddress returns true if it is our address.
  141. func (a *addrBook) OurAddress(addr *p2p.NetAddress) bool {
  142. a.mtx.Lock()
  143. defer a.mtx.Unlock()
  144. _, ok := a.ourAddrs[addr.String()]
  145. return ok
  146. }
  147. func (a *addrBook) AddPrivateIDs(IDs []string) {
  148. a.mtx.Lock()
  149. defer a.mtx.Unlock()
  150. for _, id := range IDs {
  151. a.privateIDs[p2p.ID(id)] = struct{}{}
  152. }
  153. }
  154. // AddAddress implements AddrBook
  155. // Add address to a "new" bucket. If it's already in one, only add it probabilistically.
  156. // Returns error if the addr is non-routable. Does not add self.
  157. // NOTE: addr must not be nil
  158. func (a *addrBook) AddAddress(addr *p2p.NetAddress, src *p2p.NetAddress) error {
  159. a.mtx.Lock()
  160. defer a.mtx.Unlock()
  161. return a.addAddress(addr, src)
  162. }
  163. // RemoveAddress implements AddrBook - removes the address from the book.
  164. func (a *addrBook) RemoveAddress(addr *p2p.NetAddress) {
  165. a.mtx.Lock()
  166. defer a.mtx.Unlock()
  167. ka := a.addrLookup[addr.ID]
  168. if ka == nil {
  169. return
  170. }
  171. a.Logger.Info("Remove address from book", "addr", addr)
  172. a.removeFromAllBuckets(ka)
  173. }
  174. // IsGood returns true if peer was ever marked as good and haven't
  175. // done anything wrong since then.
  176. func (a *addrBook) IsGood(addr *p2p.NetAddress) bool {
  177. a.mtx.Lock()
  178. defer a.mtx.Unlock()
  179. return a.addrLookup[addr.ID].isOld()
  180. }
  181. // HasAddress returns true if the address is in the book.
  182. func (a *addrBook) HasAddress(addr *p2p.NetAddress) bool {
  183. a.mtx.Lock()
  184. defer a.mtx.Unlock()
  185. ka := a.addrLookup[addr.ID]
  186. return ka != nil
  187. }
  188. // NeedMoreAddrs implements AddrBook - returns true if there are not have enough addresses in the book.
  189. func (a *addrBook) NeedMoreAddrs() bool {
  190. return a.Size() < needAddressThreshold
  191. }
  192. // Empty implements AddrBook - returns true if there are no addresses in the address book.
  193. // Does not count the peer appearing in its own address book, or private peers.
  194. func (a *addrBook) Empty() bool {
  195. return a.Size() == 0
  196. }
  197. // PickAddress implements AddrBook. It picks an address to connect to.
  198. // The address is picked randomly from an old or new bucket according
  199. // to the biasTowardsNewAddrs argument, which must be between [0, 100] (or else is truncated to that range)
  200. // and determines how biased we are to pick an address from a new bucket.
  201. // PickAddress returns nil if the AddrBook is empty or if we try to pick
  202. // from an empty bucket.
  203. func (a *addrBook) PickAddress(biasTowardsNewAddrs int) *p2p.NetAddress {
  204. a.mtx.Lock()
  205. defer a.mtx.Unlock()
  206. bookSize := a.size()
  207. if bookSize <= 0 {
  208. if bookSize < 0 {
  209. a.Logger.Error("Addrbook size less than 0", "nNew", a.nNew, "nOld", a.nOld)
  210. }
  211. return nil
  212. }
  213. if biasTowardsNewAddrs > 100 {
  214. biasTowardsNewAddrs = 100
  215. }
  216. if biasTowardsNewAddrs < 0 {
  217. biasTowardsNewAddrs = 0
  218. }
  219. // Bias between new and old addresses.
  220. oldCorrelation := math.Sqrt(float64(a.nOld)) * (100.0 - float64(biasTowardsNewAddrs))
  221. newCorrelation := math.Sqrt(float64(a.nNew)) * float64(biasTowardsNewAddrs)
  222. // pick a random peer from a random bucket
  223. var bucket map[string]*knownAddress
  224. pickFromOldBucket := (newCorrelation+oldCorrelation)*a.rand.Float64() < oldCorrelation
  225. if (pickFromOldBucket && a.nOld == 0) ||
  226. (!pickFromOldBucket && a.nNew == 0) {
  227. return nil
  228. }
  229. // loop until we pick a random non-empty bucket
  230. for len(bucket) == 0 {
  231. if pickFromOldBucket {
  232. bucket = a.bucketsOld[a.rand.Intn(len(a.bucketsOld))]
  233. } else {
  234. bucket = a.bucketsNew[a.rand.Intn(len(a.bucketsNew))]
  235. }
  236. }
  237. // pick a random index and loop over the map to return that index
  238. randIndex := a.rand.Intn(len(bucket))
  239. for _, ka := range bucket {
  240. if randIndex == 0 {
  241. return ka.Addr
  242. }
  243. randIndex--
  244. }
  245. return nil
  246. }
  247. // MarkGood implements AddrBook - it marks the peer as good and
  248. // moves it into an "old" bucket.
  249. func (a *addrBook) MarkGood(addr *p2p.NetAddress) {
  250. a.mtx.Lock()
  251. defer a.mtx.Unlock()
  252. ka := a.addrLookup[addr.ID]
  253. if ka == nil {
  254. return
  255. }
  256. ka.markGood()
  257. if ka.isNew() {
  258. a.moveToOld(ka)
  259. }
  260. }
  261. // MarkAttempt implements AddrBook - it marks that an attempt was made to connect to the address.
  262. func (a *addrBook) MarkAttempt(addr *p2p.NetAddress) {
  263. a.mtx.Lock()
  264. defer a.mtx.Unlock()
  265. ka := a.addrLookup[addr.ID]
  266. if ka == nil {
  267. return
  268. }
  269. ka.markAttempt()
  270. }
  271. // MarkBad implements AddrBook. Currently it just ejects the address.
  272. // TODO: black list for some amount of time
  273. func (a *addrBook) MarkBad(addr *p2p.NetAddress) {
  274. a.RemoveAddress(addr)
  275. }
  276. // GetSelection implements AddrBook.
  277. // It randomly selects some addresses (old & new). Suitable for peer-exchange protocols.
  278. // Must never return a nil address.
  279. func (a *addrBook) GetSelection() []*p2p.NetAddress {
  280. a.mtx.Lock()
  281. defer a.mtx.Unlock()
  282. bookSize := a.size()
  283. if bookSize <= 0 {
  284. if bookSize < 0 {
  285. a.Logger.Error("Addrbook size less than 0", "nNew", a.nNew, "nOld", a.nOld)
  286. }
  287. return nil
  288. }
  289. numAddresses := cmn.MaxInt(
  290. cmn.MinInt(minGetSelection, bookSize),
  291. bookSize*getSelectionPercent/100)
  292. numAddresses = cmn.MinInt(maxGetSelection, numAddresses)
  293. // XXX: instead of making a list of all addresses, shuffling, and slicing a random chunk,
  294. // could we just select a random numAddresses of indexes?
  295. allAddr := make([]*p2p.NetAddress, bookSize)
  296. i := 0
  297. for _, ka := range a.addrLookup {
  298. allAddr[i] = ka.Addr
  299. i++
  300. }
  301. // Fisher-Yates shuffle the array. We only need to do the first
  302. // `numAddresses' since we are throwing the rest.
  303. for i := 0; i < numAddresses; i++ {
  304. // pick a number between current index and the end
  305. j := cmn.RandIntn(len(allAddr)-i) + i
  306. allAddr[i], allAddr[j] = allAddr[j], allAddr[i]
  307. }
  308. // slice off the limit we are willing to share.
  309. return allAddr[:numAddresses]
  310. }
  311. func percentageOfNum(p, n int) int {
  312. return int(math.Round((float64(p) / float64(100)) * float64(n)))
  313. }
  314. // GetSelectionWithBias implements AddrBook.
  315. // It randomly selects some addresses (old & new). Suitable for peer-exchange protocols.
  316. // Must never return a nil address.
  317. //
  318. // Each address is picked randomly from an old or new bucket according to the
  319. // biasTowardsNewAddrs argument, which must be between [0, 100] (or else is truncated to
  320. // that range) and determines how biased we are to pick an address from a new
  321. // bucket.
  322. func (a *addrBook) GetSelectionWithBias(biasTowardsNewAddrs int) []*p2p.NetAddress {
  323. a.mtx.Lock()
  324. defer a.mtx.Unlock()
  325. bookSize := a.size()
  326. if bookSize <= 0 {
  327. if bookSize < 0 {
  328. a.Logger.Error("Addrbook size less than 0", "nNew", a.nNew, "nOld", a.nOld)
  329. }
  330. return nil
  331. }
  332. if biasTowardsNewAddrs > 100 {
  333. biasTowardsNewAddrs = 100
  334. }
  335. if biasTowardsNewAddrs < 0 {
  336. biasTowardsNewAddrs = 0
  337. }
  338. numAddresses := cmn.MaxInt(
  339. cmn.MinInt(minGetSelection, bookSize),
  340. bookSize*getSelectionPercent/100)
  341. numAddresses = cmn.MinInt(maxGetSelection, numAddresses)
  342. // number of new addresses that, if possible, should be in the beginning of the selection
  343. // if there are no enough old addrs, will choose new addr instead.
  344. numRequiredNewAdd := cmn.MaxInt(percentageOfNum(biasTowardsNewAddrs, numAddresses), numAddresses-a.nOld)
  345. selection := a.randomPickAddresses(bucketTypeNew, numRequiredNewAdd)
  346. selection = append(selection, a.randomPickAddresses(bucketTypeOld, numAddresses-len(selection))...)
  347. return selection
  348. }
  349. // ListOfKnownAddresses returns the new and old addresses.
  350. func (a *addrBook) ListOfKnownAddresses() []*knownAddress {
  351. a.mtx.Lock()
  352. defer a.mtx.Unlock()
  353. addrs := []*knownAddress{}
  354. for _, addr := range a.addrLookup {
  355. addrs = append(addrs, addr.copy())
  356. }
  357. return addrs
  358. }
  359. //------------------------------------------------
  360. // Size returns the number of addresses in the book.
  361. func (a *addrBook) Size() int {
  362. a.mtx.Lock()
  363. defer a.mtx.Unlock()
  364. return a.size()
  365. }
  366. func (a *addrBook) size() int {
  367. return a.nNew + a.nOld
  368. }
  369. //----------------------------------------------------------
  370. // Save persists the address book to disk.
  371. func (a *addrBook) Save() {
  372. a.saveToFile(a.filePath) // thread safe
  373. }
  374. func (a *addrBook) saveRoutine() {
  375. defer a.wg.Done()
  376. saveFileTicker := time.NewTicker(dumpAddressInterval)
  377. out:
  378. for {
  379. select {
  380. case <-saveFileTicker.C:
  381. a.saveToFile(a.filePath)
  382. case <-a.Quit():
  383. break out
  384. }
  385. }
  386. saveFileTicker.Stop()
  387. a.saveToFile(a.filePath)
  388. }
  389. //----------------------------------------------------------
  390. func (a *addrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAddress {
  391. switch bucketType {
  392. case bucketTypeNew:
  393. return a.bucketsNew[bucketIdx]
  394. case bucketTypeOld:
  395. return a.bucketsOld[bucketIdx]
  396. default:
  397. cmn.PanicSanity("Should not happen")
  398. return nil
  399. }
  400. }
  401. // Adds ka to new bucket. Returns false if it couldn't do it cuz buckets full.
  402. // NOTE: currently it always returns true.
  403. func (a *addrBook) addToNewBucket(ka *knownAddress, bucketIdx int) {
  404. // Sanity check
  405. if ka.isOld() {
  406. a.Logger.Error("Failed Sanity Check! Cant add old address to new bucket", "ka", ka, "bucket", bucketIdx)
  407. return
  408. }
  409. addrStr := ka.Addr.String()
  410. bucket := a.getBucket(bucketTypeNew, bucketIdx)
  411. // Already exists?
  412. if _, ok := bucket[addrStr]; ok {
  413. return
  414. }
  415. // Enforce max addresses.
  416. if len(bucket) > newBucketSize {
  417. a.Logger.Info("new bucket is full, expiring new")
  418. a.expireNew(bucketIdx)
  419. }
  420. // Add to bucket.
  421. bucket[addrStr] = ka
  422. // increment nNew if the peer doesnt already exist in a bucket
  423. if ka.addBucketRef(bucketIdx) == 1 {
  424. a.nNew++
  425. }
  426. // Add it to addrLookup
  427. a.addrLookup[ka.ID()] = ka
  428. }
  429. // Adds ka to old bucket. Returns false if it couldn't do it cuz buckets full.
  430. func (a *addrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool {
  431. // Sanity check
  432. if ka.isNew() {
  433. a.Logger.Error(fmt.Sprintf("Cannot add new address to old bucket: %v", ka))
  434. return false
  435. }
  436. if len(ka.Buckets) != 0 {
  437. a.Logger.Error(fmt.Sprintf("Cannot add already old address to another old bucket: %v", ka))
  438. return false
  439. }
  440. addrStr := ka.Addr.String()
  441. bucket := a.getBucket(bucketTypeOld, bucketIdx)
  442. // Already exists?
  443. if _, ok := bucket[addrStr]; ok {
  444. return true
  445. }
  446. // Enforce max addresses.
  447. if len(bucket) > oldBucketSize {
  448. return false
  449. }
  450. // Add to bucket.
  451. bucket[addrStr] = ka
  452. if ka.addBucketRef(bucketIdx) == 1 {
  453. a.nOld++
  454. }
  455. // Ensure in addrLookup
  456. a.addrLookup[ka.ID()] = ka
  457. return true
  458. }
  459. func (a *addrBook) removeFromBucket(ka *knownAddress, bucketType byte, bucketIdx int) {
  460. if ka.BucketType != bucketType {
  461. a.Logger.Error(fmt.Sprintf("Bucket type mismatch: %v", ka))
  462. return
  463. }
  464. bucket := a.getBucket(bucketType, bucketIdx)
  465. delete(bucket, ka.Addr.String())
  466. if ka.removeBucketRef(bucketIdx) == 0 {
  467. if bucketType == bucketTypeNew {
  468. a.nNew--
  469. } else {
  470. a.nOld--
  471. }
  472. delete(a.addrLookup, ka.ID())
  473. }
  474. }
  475. func (a *addrBook) removeFromAllBuckets(ka *knownAddress) {
  476. for _, bucketIdx := range ka.Buckets {
  477. bucket := a.getBucket(ka.BucketType, bucketIdx)
  478. delete(bucket, ka.Addr.String())
  479. }
  480. ka.Buckets = nil
  481. if ka.BucketType == bucketTypeNew {
  482. a.nNew--
  483. } else {
  484. a.nOld--
  485. }
  486. delete(a.addrLookup, ka.ID())
  487. }
  488. //----------------------------------------------------------
  489. func (a *addrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress {
  490. bucket := a.getBucket(bucketType, bucketIdx)
  491. var oldest *knownAddress
  492. for _, ka := range bucket {
  493. if oldest == nil || ka.LastAttempt.Before(oldest.LastAttempt) {
  494. oldest = ka
  495. }
  496. }
  497. return oldest
  498. }
  499. // adds the address to a "new" bucket. if its already in one,
  500. // it only adds it probabilistically
  501. func (a *addrBook) addAddress(addr, src *p2p.NetAddress) error {
  502. if addr == nil || src == nil {
  503. return ErrAddrBookNilAddr{addr, src}
  504. }
  505. if a.routabilityStrict && !addr.Routable() {
  506. return ErrAddrBookNonRoutable{addr}
  507. }
  508. if !addr.Valid() {
  509. return ErrAddrBookInvalidAddr{addr}
  510. }
  511. if !addr.HasID() {
  512. return ErrAddrBookInvalidAddrNoID{addr}
  513. }
  514. // TODO: we should track ourAddrs by ID and by IP:PORT and refuse both.
  515. if _, ok := a.ourAddrs[addr.String()]; ok {
  516. return ErrAddrBookSelf{addr}
  517. }
  518. if _, ok := a.privateIDs[addr.ID]; ok {
  519. return ErrAddrBookPrivate{addr}
  520. }
  521. if _, ok := a.privateIDs[src.ID]; ok {
  522. return ErrAddrBookPrivateSrc{src}
  523. }
  524. ka := a.addrLookup[addr.ID]
  525. if ka != nil {
  526. // If its already old and the addr is the same, ignore it.
  527. if ka.isOld() && ka.Addr.Equals(addr) {
  528. return nil
  529. }
  530. // Already in max new buckets.
  531. if len(ka.Buckets) == maxNewBucketsPerAddress {
  532. return nil
  533. }
  534. // The more entries we have, the less likely we are to add more.
  535. factor := int32(2 * len(ka.Buckets))
  536. if a.rand.Int31n(factor) != 0 {
  537. return nil
  538. }
  539. } else {
  540. ka = newKnownAddress(addr, src)
  541. }
  542. bucket := a.calcNewBucket(addr, src)
  543. a.addToNewBucket(ka, bucket)
  544. return nil
  545. }
  546. func (a *addrBook) randomPickAddresses(bucketType byte, num int) []*p2p.NetAddress {
  547. var buckets []map[string]*knownAddress
  548. switch bucketType {
  549. case bucketTypeNew:
  550. buckets = a.bucketsNew
  551. case bucketTypeOld:
  552. buckets = a.bucketsOld
  553. default:
  554. panic("unexpected bucketType")
  555. }
  556. total := 0
  557. for _, bucket := range buckets {
  558. total = total + len(bucket)
  559. }
  560. addresses := make([]*knownAddress, 0, total)
  561. for _, bucket := range buckets {
  562. for _, ka := range bucket {
  563. addresses = append(addresses, ka)
  564. }
  565. }
  566. selection := make([]*p2p.NetAddress, 0, num)
  567. chosenSet := make(map[string]bool, num)
  568. rand.Shuffle(total, func(i, j int) {
  569. addresses[i], addresses[j] = addresses[j], addresses[i]
  570. })
  571. for _, addr := range addresses {
  572. if chosenSet[addr.Addr.String()] {
  573. continue
  574. }
  575. chosenSet[addr.Addr.String()] = true
  576. selection = append(selection, addr.Addr)
  577. if len(selection) >= num {
  578. return selection
  579. }
  580. }
  581. return selection
  582. }
  583. // Make space in the new buckets by expiring the really bad entries.
  584. // If no bad entries are available we remove the oldest.
  585. func (a *addrBook) expireNew(bucketIdx int) {
  586. for addrStr, ka := range a.bucketsNew[bucketIdx] {
  587. // If an entry is bad, throw it away
  588. if ka.isBad() {
  589. a.Logger.Info(fmt.Sprintf("expiring bad address %v", addrStr))
  590. a.removeFromBucket(ka, bucketTypeNew, bucketIdx)
  591. return
  592. }
  593. }
  594. // If we haven't thrown out a bad entry, throw out the oldest entry
  595. oldest := a.pickOldest(bucketTypeNew, bucketIdx)
  596. a.removeFromBucket(oldest, bucketTypeNew, bucketIdx)
  597. }
  598. // Promotes an address from new to old. If the destination bucket is full,
  599. // demote the oldest one to a "new" bucket.
  600. // TODO: Demote more probabilistically?
  601. func (a *addrBook) moveToOld(ka *knownAddress) {
  602. // Sanity check
  603. if ka.isOld() {
  604. a.Logger.Error(fmt.Sprintf("Cannot promote address that is already old %v", ka))
  605. return
  606. }
  607. if len(ka.Buckets) == 0 {
  608. a.Logger.Error(fmt.Sprintf("Cannot promote address that isn't in any new buckets %v", ka))
  609. return
  610. }
  611. // Remove from all (new) buckets.
  612. a.removeFromAllBuckets(ka)
  613. // It's officially old now.
  614. ka.BucketType = bucketTypeOld
  615. // Try to add it to its oldBucket destination.
  616. oldBucketIdx := a.calcOldBucket(ka.Addr)
  617. added := a.addToOldBucket(ka, oldBucketIdx)
  618. if !added {
  619. // No room; move the oldest to a new bucket
  620. oldest := a.pickOldest(bucketTypeOld, oldBucketIdx)
  621. a.removeFromBucket(oldest, bucketTypeOld, oldBucketIdx)
  622. newBucketIdx := a.calcNewBucket(oldest.Addr, oldest.Src)
  623. a.addToNewBucket(oldest, newBucketIdx)
  624. // Finally, add our ka to old bucket again.
  625. added = a.addToOldBucket(ka, oldBucketIdx)
  626. if !added {
  627. a.Logger.Error(fmt.Sprintf("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx))
  628. }
  629. }
  630. }
  631. //---------------------------------------------------------------------
  632. // calculate bucket placements
  633. // doublesha256( key + sourcegroup +
  634. // int64(doublesha256(key + group + sourcegroup))%bucket_per_group ) % num_new_buckets
  635. func (a *addrBook) calcNewBucket(addr, src *p2p.NetAddress) int {
  636. data1 := []byte{}
  637. data1 = append(data1, []byte(a.key)...)
  638. data1 = append(data1, []byte(a.groupKey(addr))...)
  639. data1 = append(data1, []byte(a.groupKey(src))...)
  640. hash1 := doubleSha256(data1)
  641. hash64 := binary.BigEndian.Uint64(hash1)
  642. hash64 %= newBucketsPerGroup
  643. var hashbuf [8]byte
  644. binary.BigEndian.PutUint64(hashbuf[:], hash64)
  645. data2 := []byte{}
  646. data2 = append(data2, []byte(a.key)...)
  647. data2 = append(data2, a.groupKey(src)...)
  648. data2 = append(data2, hashbuf[:]...)
  649. hash2 := doubleSha256(data2)
  650. return int(binary.BigEndian.Uint64(hash2) % newBucketCount)
  651. }
  652. // doublesha256( key + group +
  653. // int64(doublesha256(key + addr))%buckets_per_group ) % num_old_buckets
  654. func (a *addrBook) calcOldBucket(addr *p2p.NetAddress) int {
  655. data1 := []byte{}
  656. data1 = append(data1, []byte(a.key)...)
  657. data1 = append(data1, []byte(addr.String())...)
  658. hash1 := doubleSha256(data1)
  659. hash64 := binary.BigEndian.Uint64(hash1)
  660. hash64 %= oldBucketsPerGroup
  661. var hashbuf [8]byte
  662. binary.BigEndian.PutUint64(hashbuf[:], hash64)
  663. data2 := []byte{}
  664. data2 = append(data2, []byte(a.key)...)
  665. data2 = append(data2, a.groupKey(addr)...)
  666. data2 = append(data2, hashbuf[:]...)
  667. hash2 := doubleSha256(data2)
  668. return int(binary.BigEndian.Uint64(hash2) % oldBucketCount)
  669. }
  670. // Return a string representing the network group of this address.
  671. // This is the /16 for IPv4, the /32 (/36 for he.net) for IPv6, the string
  672. // "local" for a local address and the string "unroutable" for an unroutable
  673. // address.
  674. func (a *addrBook) groupKey(na *p2p.NetAddress) string {
  675. if a.routabilityStrict && na.Local() {
  676. return "local"
  677. }
  678. if a.routabilityStrict && !na.Routable() {
  679. return "unroutable"
  680. }
  681. if ipv4 := na.IP.To4(); ipv4 != nil {
  682. return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(16, 32)}).String()
  683. }
  684. if na.RFC6145() || na.RFC6052() {
  685. // last four bytes are the ip address
  686. ip := net.IP(na.IP[12:16])
  687. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  688. }
  689. if na.RFC3964() {
  690. ip := net.IP(na.IP[2:7])
  691. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  692. }
  693. if na.RFC4380() {
  694. // teredo tunnels have the last 4 bytes as the v4 address XOR
  695. // 0xff.
  696. ip := net.IP(make([]byte, 4))
  697. for i, byte := range na.IP[12:16] {
  698. ip[i] = byte ^ 0xff
  699. }
  700. return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String()
  701. }
  702. // OK, so now we know ourselves to be a IPv6 address.
  703. // bitcoind uses /32 for everything, except for Hurricane Electric's
  704. // (he.net) IP range, which it uses /36 for.
  705. bits := 32
  706. heNet := &net.IPNet{IP: net.ParseIP("2001:470::"),
  707. Mask: net.CIDRMask(32, 128)}
  708. if heNet.Contains(na.IP) {
  709. bits = 36
  710. }
  711. return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(bits, 128)}).String()
  712. }
  713. // doubleSha256 calculates sha256(sha256(b)) and returns the resulting bytes.
  714. func doubleSha256(b []byte) []byte {
  715. hasher := sha256.New()
  716. hasher.Write(b) // nolint: errcheck, gas
  717. sum := hasher.Sum(nil)
  718. hasher.Reset()
  719. hasher.Write(sum) // nolint: errcheck, gas
  720. return hasher.Sum(nil)
  721. }