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.

886 lines
24 KiB

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