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.

838 lines
23 KiB

p2p: file descriptor leaks (#3150) * close peer's connection to avoid fd leak Fixes #2967 * rename peer#Addr to RemoteAddr * fix test * fixes after Ethan's review * bring back the check * changelog entry * write a test for switch#acceptRoutine * increase timeouts? :( * remove extra assertNPeersWithTimeout * simplify test * assert number of peers (just to be safe) * Cleanup in OnStop * run tests with verbose flag on CircleCI * spawn a reading routine to prevent connection from closing * get port from the listener random port is faster, but often results in ``` panic: listen tcp 127.0.0.1:44068: bind: address already in use [recovered] panic: listen tcp 127.0.0.1:44068: bind: address already in use goroutine 79 [running]: testing.tRunner.func1(0xc0001bd600) /usr/local/go/src/testing/testing.go:792 +0x387 panic(0x974d20, 0xc0001b0500) /usr/local/go/src/runtime/panic.go:513 +0x1b9 github.com/tendermint/tendermint/p2p.MakeSwitch(0xc0000f42a0, 0x0, 0x9fb9cc, 0x9, 0x9fc346, 0xb, 0xb42128, 0x0, 0x0, 0x0, ...) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:182 +0xa28 github.com/tendermint/tendermint/p2p.MakeConnectedSwitches(0xc0000f42a0, 0x2, 0xb42128, 0xb41eb8, 0x4f1205, 0xc0001bed80, 0x4f16ed) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:75 +0xf9 github.com/tendermint/tendermint/p2p.MakeSwitchPair(0xbb8d20, 0xc0001bd600, 0xb42128, 0x2f7, 0x4f16c0) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:94 +0x4c github.com/tendermint/tendermint/p2p.TestSwitches(0xc0001bd600) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:117 +0x58 testing.tRunner(0xc0001bd600, 0xb42038) /usr/local/go/src/testing/testing.go:827 +0xbf created by testing.(*T).Run /usr/local/go/src/testing/testing.go:878 +0x353 exit status 2 FAIL github.com/tendermint/tendermint/p2p 0.350s ```
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: 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: 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: 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: file descriptor leaks (#3150) * close peer's connection to avoid fd leak Fixes #2967 * rename peer#Addr to RemoteAddr * fix test * fixes after Ethan's review * bring back the check * changelog entry * write a test for switch#acceptRoutine * increase timeouts? :( * remove extra assertNPeersWithTimeout * simplify test * assert number of peers (just to be safe) * Cleanup in OnStop * run tests with verbose flag on CircleCI * spawn a reading routine to prevent connection from closing * get port from the listener random port is faster, but often results in ``` panic: listen tcp 127.0.0.1:44068: bind: address already in use [recovered] panic: listen tcp 127.0.0.1:44068: bind: address already in use goroutine 79 [running]: testing.tRunner.func1(0xc0001bd600) /usr/local/go/src/testing/testing.go:792 +0x387 panic(0x974d20, 0xc0001b0500) /usr/local/go/src/runtime/panic.go:513 +0x1b9 github.com/tendermint/tendermint/p2p.MakeSwitch(0xc0000f42a0, 0x0, 0x9fb9cc, 0x9, 0x9fc346, 0xb, 0xb42128, 0x0, 0x0, 0x0, ...) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:182 +0xa28 github.com/tendermint/tendermint/p2p.MakeConnectedSwitches(0xc0000f42a0, 0x2, 0xb42128, 0xb41eb8, 0x4f1205, 0xc0001bed80, 0x4f16ed) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:75 +0xf9 github.com/tendermint/tendermint/p2p.MakeSwitchPair(0xbb8d20, 0xc0001bd600, 0xb42128, 0x2f7, 0x4f16c0) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:94 +0x4c github.com/tendermint/tendermint/p2p.TestSwitches(0xc0001bd600) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:117 +0x58 testing.tRunner(0xc0001bd600, 0xb42038) /usr/local/go/src/testing/testing.go:827 +0xbf created by testing.(*T).Run /usr/local/go/src/testing/testing.go:878 +0x353 exit status 2 FAIL github.com/tendermint/tendermint/p2p 0.350s ```
6 years ago
p2p: file descriptor leaks (#3150) * close peer's connection to avoid fd leak Fixes #2967 * rename peer#Addr to RemoteAddr * fix test * fixes after Ethan's review * bring back the check * changelog entry * write a test for switch#acceptRoutine * increase timeouts? :( * remove extra assertNPeersWithTimeout * simplify test * assert number of peers (just to be safe) * Cleanup in OnStop * run tests with verbose flag on CircleCI * spawn a reading routine to prevent connection from closing * get port from the listener random port is faster, but often results in ``` panic: listen tcp 127.0.0.1:44068: bind: address already in use [recovered] panic: listen tcp 127.0.0.1:44068: bind: address already in use goroutine 79 [running]: testing.tRunner.func1(0xc0001bd600) /usr/local/go/src/testing/testing.go:792 +0x387 panic(0x974d20, 0xc0001b0500) /usr/local/go/src/runtime/panic.go:513 +0x1b9 github.com/tendermint/tendermint/p2p.MakeSwitch(0xc0000f42a0, 0x0, 0x9fb9cc, 0x9, 0x9fc346, 0xb, 0xb42128, 0x0, 0x0, 0x0, ...) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:182 +0xa28 github.com/tendermint/tendermint/p2p.MakeConnectedSwitches(0xc0000f42a0, 0x2, 0xb42128, 0xb41eb8, 0x4f1205, 0xc0001bed80, 0x4f16ed) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:75 +0xf9 github.com/tendermint/tendermint/p2p.MakeSwitchPair(0xbb8d20, 0xc0001bd600, 0xb42128, 0x2f7, 0x4f16c0) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:94 +0x4c github.com/tendermint/tendermint/p2p.TestSwitches(0xc0001bd600) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:117 +0x58 testing.tRunner(0xc0001bd600, 0xb42038) /usr/local/go/src/testing/testing.go:827 +0xbf created by testing.(*T).Run /usr/local/go/src/testing/testing.go:878 +0x353 exit status 2 FAIL github.com/tendermint/tendermint/p2p 0.350s ```
6 years ago
p2p: file descriptor leaks (#3150) * close peer's connection to avoid fd leak Fixes #2967 * rename peer#Addr to RemoteAddr * fix test * fixes after Ethan's review * bring back the check * changelog entry * write a test for switch#acceptRoutine * increase timeouts? :( * remove extra assertNPeersWithTimeout * simplify test * assert number of peers (just to be safe) * Cleanup in OnStop * run tests with verbose flag on CircleCI * spawn a reading routine to prevent connection from closing * get port from the listener random port is faster, but often results in ``` panic: listen tcp 127.0.0.1:44068: bind: address already in use [recovered] panic: listen tcp 127.0.0.1:44068: bind: address already in use goroutine 79 [running]: testing.tRunner.func1(0xc0001bd600) /usr/local/go/src/testing/testing.go:792 +0x387 panic(0x974d20, 0xc0001b0500) /usr/local/go/src/runtime/panic.go:513 +0x1b9 github.com/tendermint/tendermint/p2p.MakeSwitch(0xc0000f42a0, 0x0, 0x9fb9cc, 0x9, 0x9fc346, 0xb, 0xb42128, 0x0, 0x0, 0x0, ...) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:182 +0xa28 github.com/tendermint/tendermint/p2p.MakeConnectedSwitches(0xc0000f42a0, 0x2, 0xb42128, 0xb41eb8, 0x4f1205, 0xc0001bed80, 0x4f16ed) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:75 +0xf9 github.com/tendermint/tendermint/p2p.MakeSwitchPair(0xbb8d20, 0xc0001bd600, 0xb42128, 0x2f7, 0x4f16c0) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:94 +0x4c github.com/tendermint/tendermint/p2p.TestSwitches(0xc0001bd600) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:117 +0x58 testing.tRunner(0xc0001bd600, 0xb42038) /usr/local/go/src/testing/testing.go:827 +0xbf created by testing.(*T).Run /usr/local/go/src/testing/testing.go:878 +0x353 exit status 2 FAIL github.com/tendermint/tendermint/p2p 0.350s ```
6 years ago
p2p: file descriptor leaks (#3150) * close peer's connection to avoid fd leak Fixes #2967 * rename peer#Addr to RemoteAddr * fix test * fixes after Ethan's review * bring back the check * changelog entry * write a test for switch#acceptRoutine * increase timeouts? :( * remove extra assertNPeersWithTimeout * simplify test * assert number of peers (just to be safe) * Cleanup in OnStop * run tests with verbose flag on CircleCI * spawn a reading routine to prevent connection from closing * get port from the listener random port is faster, but often results in ``` panic: listen tcp 127.0.0.1:44068: bind: address already in use [recovered] panic: listen tcp 127.0.0.1:44068: bind: address already in use goroutine 79 [running]: testing.tRunner.func1(0xc0001bd600) /usr/local/go/src/testing/testing.go:792 +0x387 panic(0x974d20, 0xc0001b0500) /usr/local/go/src/runtime/panic.go:513 +0x1b9 github.com/tendermint/tendermint/p2p.MakeSwitch(0xc0000f42a0, 0x0, 0x9fb9cc, 0x9, 0x9fc346, 0xb, 0xb42128, 0x0, 0x0, 0x0, ...) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:182 +0xa28 github.com/tendermint/tendermint/p2p.MakeConnectedSwitches(0xc0000f42a0, 0x2, 0xb42128, 0xb41eb8, 0x4f1205, 0xc0001bed80, 0x4f16ed) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:75 +0xf9 github.com/tendermint/tendermint/p2p.MakeSwitchPair(0xbb8d20, 0xc0001bd600, 0xb42128, 0x2f7, 0x4f16c0) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:94 +0x4c github.com/tendermint/tendermint/p2p.TestSwitches(0xc0001bd600) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:117 +0x58 testing.tRunner(0xc0001bd600, 0xb42038) /usr/local/go/src/testing/testing.go:827 +0xbf created by testing.(*T).Run /usr/local/go/src/testing/testing.go:878 +0x353 exit status 2 FAIL github.com/tendermint/tendermint/p2p 0.350s ```
6 years ago
p2p: file descriptor leaks (#3150) * close peer's connection to avoid fd leak Fixes #2967 * rename peer#Addr to RemoteAddr * fix test * fixes after Ethan's review * bring back the check * changelog entry * write a test for switch#acceptRoutine * increase timeouts? :( * remove extra assertNPeersWithTimeout * simplify test * assert number of peers (just to be safe) * Cleanup in OnStop * run tests with verbose flag on CircleCI * spawn a reading routine to prevent connection from closing * get port from the listener random port is faster, but often results in ``` panic: listen tcp 127.0.0.1:44068: bind: address already in use [recovered] panic: listen tcp 127.0.0.1:44068: bind: address already in use goroutine 79 [running]: testing.tRunner.func1(0xc0001bd600) /usr/local/go/src/testing/testing.go:792 +0x387 panic(0x974d20, 0xc0001b0500) /usr/local/go/src/runtime/panic.go:513 +0x1b9 github.com/tendermint/tendermint/p2p.MakeSwitch(0xc0000f42a0, 0x0, 0x9fb9cc, 0x9, 0x9fc346, 0xb, 0xb42128, 0x0, 0x0, 0x0, ...) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:182 +0xa28 github.com/tendermint/tendermint/p2p.MakeConnectedSwitches(0xc0000f42a0, 0x2, 0xb42128, 0xb41eb8, 0x4f1205, 0xc0001bed80, 0x4f16ed) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/test_util.go:75 +0xf9 github.com/tendermint/tendermint/p2p.MakeSwitchPair(0xbb8d20, 0xc0001bd600, 0xb42128, 0x2f7, 0x4f16c0) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:94 +0x4c github.com/tendermint/tendermint/p2p.TestSwitches(0xc0001bd600) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch_test.go:117 +0x58 testing.tRunner(0xc0001bd600, 0xb42038) /usr/local/go/src/testing/testing.go:827 +0xbf created by testing.(*T).Run /usr/local/go/src/testing/testing.go:878 +0x353 exit status 2 FAIL github.com/tendermint/tendermint/p2p 0.350s ```
6 years ago
  1. package p2p
  2. import (
  3. "fmt"
  4. "math"
  5. "sync"
  6. "time"
  7. "github.com/tendermint/tendermint/config"
  8. "github.com/tendermint/tendermint/libs/cmap"
  9. "github.com/tendermint/tendermint/libs/rand"
  10. "github.com/tendermint/tendermint/libs/service"
  11. "github.com/tendermint/tendermint/p2p/conn"
  12. )
  13. const (
  14. // wait a random amount of time from this interval
  15. // before dialing peers or reconnecting to help prevent DoS
  16. dialRandomizerIntervalMilliseconds = 3000
  17. // repeatedly try to reconnect for a few minutes
  18. // ie. 5 * 20 = 100s
  19. reconnectAttempts = 20
  20. reconnectInterval = 5 * time.Second
  21. // then move into exponential backoff mode for ~1day
  22. // ie. 3**10 = 16hrs
  23. reconnectBackOffAttempts = 10
  24. reconnectBackOffBaseSeconds = 3
  25. )
  26. // MConnConfig returns an MConnConfig with fields updated
  27. // from the P2PConfig.
  28. func MConnConfig(cfg *config.P2PConfig) conn.MConnConfig {
  29. mConfig := conn.DefaultMConnConfig()
  30. mConfig.FlushThrottle = cfg.FlushThrottleTimeout
  31. mConfig.SendRate = cfg.SendRate
  32. mConfig.RecvRate = cfg.RecvRate
  33. mConfig.MaxPacketMsgPayloadSize = cfg.MaxPacketMsgPayloadSize
  34. return mConfig
  35. }
  36. //-----------------------------------------------------------------------------
  37. // An AddrBook represents an address book from the pex package, which is used
  38. // to store peer addresses.
  39. type AddrBook interface {
  40. AddAddress(addr *NetAddress, src *NetAddress) error
  41. AddPrivateIDs([]string)
  42. AddOurAddress(*NetAddress)
  43. OurAddress(*NetAddress) bool
  44. MarkGood(ID)
  45. RemoveAddress(*NetAddress)
  46. HasAddress(*NetAddress) bool
  47. Save()
  48. }
  49. // PeerFilterFunc to be implemented by filter hooks after a new Peer has been
  50. // fully setup.
  51. type PeerFilterFunc func(IPeerSet, Peer) error
  52. //-----------------------------------------------------------------------------
  53. // Switch handles peer connections and exposes an API to receive incoming messages
  54. // on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one
  55. // or more `Channels`. So while sending outgoing messages is typically performed on the peer,
  56. // incoming messages are received on the reactor.
  57. type Switch struct {
  58. service.BaseService
  59. config *config.P2PConfig
  60. reactors map[string]Reactor
  61. chDescs []*conn.ChannelDescriptor
  62. reactorsByCh map[byte]Reactor
  63. peers *PeerSet
  64. dialing *cmap.CMap
  65. reconnecting *cmap.CMap
  66. nodeInfo NodeInfo // our node info
  67. nodeKey NodeKey // our node privkey
  68. addrBook AddrBook
  69. // peers addresses with whom we'll maintain constant connection
  70. persistentPeersAddrs []*NetAddress
  71. unconditionalPeerIDs map[ID]struct{}
  72. transport Transport
  73. filterTimeout time.Duration
  74. peerFilters []PeerFilterFunc
  75. rng *rand.Rand // seed for randomizing dial times and orders
  76. metrics *Metrics
  77. }
  78. // NetAddress returns the address the switch is listening on.
  79. func (sw *Switch) NetAddress() *NetAddress {
  80. addr := sw.transport.NetAddress()
  81. return &addr
  82. }
  83. // SwitchOption sets an optional parameter on the Switch.
  84. type SwitchOption func(*Switch)
  85. // NewSwitch creates a new Switch with the given config.
  86. func NewSwitch(
  87. cfg *config.P2PConfig,
  88. transport Transport,
  89. options ...SwitchOption,
  90. ) *Switch {
  91. sw := &Switch{
  92. config: cfg,
  93. reactors: make(map[string]Reactor),
  94. chDescs: make([]*conn.ChannelDescriptor, 0),
  95. reactorsByCh: make(map[byte]Reactor),
  96. peers: NewPeerSet(),
  97. dialing: cmap.NewCMap(),
  98. reconnecting: cmap.NewCMap(),
  99. metrics: NopMetrics(),
  100. transport: transport,
  101. filterTimeout: defaultFilterTimeout,
  102. persistentPeersAddrs: make([]*NetAddress, 0),
  103. unconditionalPeerIDs: make(map[ID]struct{}),
  104. }
  105. // Ensure we have a completely undeterministic PRNG.
  106. sw.rng = rand.NewRand()
  107. sw.BaseService = *service.NewBaseService(nil, "P2P Switch", sw)
  108. for _, option := range options {
  109. option(sw)
  110. }
  111. return sw
  112. }
  113. // SwitchFilterTimeout sets the timeout used for peer filters.
  114. func SwitchFilterTimeout(timeout time.Duration) SwitchOption {
  115. return func(sw *Switch) { sw.filterTimeout = timeout }
  116. }
  117. // SwitchPeerFilters sets the filters for rejection of new peers.
  118. func SwitchPeerFilters(filters ...PeerFilterFunc) SwitchOption {
  119. return func(sw *Switch) { sw.peerFilters = filters }
  120. }
  121. // WithMetrics sets the metrics.
  122. func WithMetrics(metrics *Metrics) SwitchOption {
  123. return func(sw *Switch) { sw.metrics = metrics }
  124. }
  125. //---------------------------------------------------------------------
  126. // Switch setup
  127. // AddReactor adds the given reactor to the switch.
  128. // NOTE: Not goroutine safe.
  129. func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor {
  130. for _, chDesc := range reactor.GetChannels() {
  131. chID := chDesc.ID
  132. // No two reactors can share the same channel.
  133. if sw.reactorsByCh[chID] != nil {
  134. panic(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor))
  135. }
  136. sw.chDescs = append(sw.chDescs, chDesc)
  137. sw.reactorsByCh[chID] = reactor
  138. }
  139. sw.reactors[name] = reactor
  140. reactor.SetSwitch(sw)
  141. return reactor
  142. }
  143. // RemoveReactor removes the given Reactor from the Switch.
  144. // NOTE: Not goroutine safe.
  145. func (sw *Switch) RemoveReactor(name string, reactor Reactor) {
  146. for _, chDesc := range reactor.GetChannels() {
  147. // remove channel description
  148. for i := 0; i < len(sw.chDescs); i++ {
  149. if chDesc.ID == sw.chDescs[i].ID {
  150. sw.chDescs = append(sw.chDescs[:i], sw.chDescs[i+1:]...)
  151. break
  152. }
  153. }
  154. delete(sw.reactorsByCh, chDesc.ID)
  155. }
  156. delete(sw.reactors, name)
  157. reactor.SetSwitch(nil)
  158. }
  159. // Reactors returns a map of reactors registered on the switch.
  160. // NOTE: Not goroutine safe.
  161. func (sw *Switch) Reactors() map[string]Reactor {
  162. return sw.reactors
  163. }
  164. // Reactor returns the reactor with the given name.
  165. // NOTE: Not goroutine safe.
  166. func (sw *Switch) Reactor(name string) Reactor {
  167. return sw.reactors[name]
  168. }
  169. // SetNodeInfo sets the switch's NodeInfo for checking compatibility and handshaking with other nodes.
  170. // NOTE: Not goroutine safe.
  171. func (sw *Switch) SetNodeInfo(nodeInfo NodeInfo) {
  172. sw.nodeInfo = nodeInfo
  173. }
  174. // NodeInfo returns the switch's NodeInfo.
  175. // NOTE: Not goroutine safe.
  176. func (sw *Switch) NodeInfo() NodeInfo {
  177. return sw.nodeInfo
  178. }
  179. // SetNodeKey sets the switch's private key for authenticated encryption.
  180. // NOTE: Not goroutine safe.
  181. func (sw *Switch) SetNodeKey(nodeKey NodeKey) {
  182. sw.nodeKey = nodeKey
  183. }
  184. //---------------------------------------------------------------------
  185. // Service start/stop
  186. // OnStart implements BaseService. It starts all the reactors and peers.
  187. func (sw *Switch) OnStart() error {
  188. // Start reactors
  189. for _, reactor := range sw.reactors {
  190. err := reactor.Start()
  191. if err != nil {
  192. return fmt.Errorf("failed to start %v: %w", reactor, err)
  193. }
  194. }
  195. // Start accepting Peers.
  196. go sw.acceptRoutine()
  197. return nil
  198. }
  199. // OnStop implements BaseService. It stops all peers and reactors.
  200. func (sw *Switch) OnStop() {
  201. // Stop peers
  202. for _, p := range sw.peers.List() {
  203. sw.stopAndRemovePeer(p, nil)
  204. }
  205. // Stop reactors
  206. sw.Logger.Debug("Switch: Stopping reactors")
  207. for _, reactor := range sw.reactors {
  208. if err := reactor.Stop(); err != nil {
  209. sw.Logger.Error("error while stopped reactor", "reactor", reactor, "error", err)
  210. }
  211. }
  212. }
  213. //---------------------------------------------------------------------
  214. // Peers
  215. // Broadcast runs a go routine for each attempted send, which will block trying
  216. // to send for defaultSendTimeoutSeconds. Returns a channel which receives
  217. // success values for each attempted send (false if times out). Channel will be
  218. // closed once msg bytes are sent to all peers (or time out).
  219. //
  220. // NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved.
  221. func (sw *Switch) Broadcast(chID byte, msgBytes []byte) chan bool {
  222. sw.Logger.Debug("Broadcast", "channel", chID, "msgBytes", fmt.Sprintf("%X", msgBytes))
  223. peers := sw.peers.List()
  224. var wg sync.WaitGroup
  225. wg.Add(len(peers))
  226. successChan := make(chan bool, len(peers))
  227. for _, peer := range peers {
  228. go func(p Peer) {
  229. defer wg.Done()
  230. success := p.Send(chID, msgBytes)
  231. successChan <- success
  232. }(peer)
  233. }
  234. go func() {
  235. wg.Wait()
  236. close(successChan)
  237. }()
  238. return successChan
  239. }
  240. // NumPeers returns the count of outbound/inbound and outbound-dialing peers.
  241. // unconditional peers are not counted here.
  242. func (sw *Switch) NumPeers() (outbound, inbound, dialing int) {
  243. peers := sw.peers.List()
  244. for _, peer := range peers {
  245. if peer.IsOutbound() {
  246. if !sw.IsPeerUnconditional(peer.ID()) {
  247. outbound++
  248. }
  249. } else {
  250. if !sw.IsPeerUnconditional(peer.ID()) {
  251. inbound++
  252. }
  253. }
  254. }
  255. dialing = sw.dialing.Size()
  256. return
  257. }
  258. func (sw *Switch) IsPeerUnconditional(id ID) bool {
  259. _, ok := sw.unconditionalPeerIDs[id]
  260. return ok
  261. }
  262. // MaxNumOutboundPeers returns a maximum number of outbound peers.
  263. func (sw *Switch) MaxNumOutboundPeers() int {
  264. return sw.config.MaxNumOutboundPeers
  265. }
  266. // Peers returns the set of peers that are connected to the switch.
  267. func (sw *Switch) Peers() IPeerSet {
  268. return sw.peers
  269. }
  270. // StopPeerForError disconnects from a peer due to external error.
  271. // If the peer is persistent, it will attempt to reconnect.
  272. // TODO: make record depending on reason.
  273. func (sw *Switch) StopPeerForError(peer Peer, reason interface{}) {
  274. if !peer.IsRunning() {
  275. return
  276. }
  277. sw.Logger.Error("Stopping peer for error", "peer", peer, "err", reason)
  278. sw.stopAndRemovePeer(peer, reason)
  279. if peer.IsPersistent() {
  280. var addr *NetAddress
  281. if peer.IsOutbound() { // socket address for outbound peers
  282. addr = peer.SocketAddr()
  283. } else { // self-reported address for inbound peers
  284. var err error
  285. addr, err = peer.NodeInfo().NetAddress()
  286. if err != nil {
  287. sw.Logger.Error("Wanted to reconnect to inbound peer, but self-reported address is wrong",
  288. "peer", peer, "err", err)
  289. return
  290. }
  291. }
  292. go sw.reconnectToPeer(addr)
  293. }
  294. }
  295. // StopPeerGracefully disconnects from a peer gracefully.
  296. // TODO: handle graceful disconnects.
  297. func (sw *Switch) StopPeerGracefully(peer Peer) {
  298. sw.Logger.Info("Stopping peer gracefully")
  299. sw.stopAndRemovePeer(peer, nil)
  300. }
  301. func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) {
  302. sw.transport.Cleanup(peer)
  303. if err := peer.Stop(); err != nil {
  304. sw.Logger.Error("error while stopping peer", "error", err) // TODO: should return error to be handled accordingly
  305. }
  306. for _, reactor := range sw.reactors {
  307. reactor.RemovePeer(peer, reason)
  308. }
  309. // Removing a peer should go last to avoid a situation where a peer
  310. // reconnect to our node and the switch calls InitPeer before
  311. // RemovePeer is finished.
  312. // https://github.com/tendermint/tendermint/issues/3338
  313. if sw.peers.Remove(peer) {
  314. sw.metrics.Peers.Add(float64(-1))
  315. }
  316. }
  317. // reconnectToPeer tries to reconnect to the addr, first repeatedly
  318. // with a fixed interval, then with exponential backoff.
  319. // If no success after all that, it stops trying, and leaves it
  320. // to the PEX/Addrbook to find the peer with the addr again
  321. // NOTE: this will keep trying even if the handshake or auth fails.
  322. // TODO: be more explicit with error types so we only retry on certain failures
  323. // - ie. if we're getting ErrDuplicatePeer we can stop
  324. // because the addrbook got us the peer back already
  325. func (sw *Switch) reconnectToPeer(addr *NetAddress) {
  326. if sw.reconnecting.Has(string(addr.ID)) {
  327. return
  328. }
  329. sw.reconnecting.Set(string(addr.ID), addr)
  330. defer sw.reconnecting.Delete(string(addr.ID))
  331. start := time.Now()
  332. sw.Logger.Info("Reconnecting to peer", "addr", addr)
  333. for i := 0; i < reconnectAttempts; i++ {
  334. if !sw.IsRunning() {
  335. return
  336. }
  337. err := sw.DialPeerWithAddress(addr)
  338. if err == nil {
  339. return // success
  340. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  341. return
  342. }
  343. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  344. // sleep a set amount
  345. sw.randomSleep(reconnectInterval)
  346. continue
  347. }
  348. sw.Logger.Error("Failed to reconnect to peer. Beginning exponential backoff",
  349. "addr", addr, "elapsed", time.Since(start))
  350. for i := 0; i < reconnectBackOffAttempts; i++ {
  351. if !sw.IsRunning() {
  352. return
  353. }
  354. // sleep an exponentially increasing amount
  355. sleepIntervalSeconds := math.Pow(reconnectBackOffBaseSeconds, float64(i))
  356. sw.randomSleep(time.Duration(sleepIntervalSeconds) * time.Second)
  357. err := sw.DialPeerWithAddress(addr)
  358. if err == nil {
  359. return // success
  360. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  361. return
  362. }
  363. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  364. }
  365. sw.Logger.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start))
  366. }
  367. // SetAddrBook allows to set address book on Switch.
  368. func (sw *Switch) SetAddrBook(addrBook AddrBook) {
  369. sw.addrBook = addrBook
  370. }
  371. // MarkPeerAsGood marks the given peer as good when it did something useful
  372. // like contributed to consensus.
  373. func (sw *Switch) MarkPeerAsGood(peer Peer) {
  374. if sw.addrBook != nil {
  375. sw.addrBook.MarkGood(peer.ID())
  376. }
  377. }
  378. //---------------------------------------------------------------------
  379. // Dialing
  380. type privateAddr interface {
  381. PrivateAddr() bool
  382. }
  383. func isPrivateAddr(err error) bool {
  384. te, ok := err.(privateAddr)
  385. return ok && te.PrivateAddr()
  386. }
  387. // DialPeersAsync dials a list of peers asynchronously in random order.
  388. // Used to dial peers from config on startup or from unsafe-RPC (trusted sources).
  389. // It ignores ErrNetAddressLookup. However, if there are other errors, first
  390. // encounter is returned.
  391. // Nop if there are no peers.
  392. func (sw *Switch) DialPeersAsync(peers []string) error {
  393. netAddrs, errs := NewNetAddressStrings(peers)
  394. // report all the errors
  395. for _, err := range errs {
  396. sw.Logger.Error("Error in peer's address", "err", err)
  397. }
  398. // return first non-ErrNetAddressLookup error
  399. for _, err := range errs {
  400. if _, ok := err.(ErrNetAddressLookup); ok {
  401. continue
  402. }
  403. return err
  404. }
  405. sw.dialPeersAsync(netAddrs)
  406. return nil
  407. }
  408. func (sw *Switch) dialPeersAsync(netAddrs []*NetAddress) {
  409. ourAddr := sw.NetAddress()
  410. // TODO: this code feels like it's in the wrong place.
  411. // The integration tests depend on the addrBook being saved
  412. // right away but maybe we can change that. Recall that
  413. // the addrBook is only written to disk every 2min
  414. if sw.addrBook != nil {
  415. // add peers to `addrBook`
  416. for _, netAddr := range netAddrs {
  417. // do not add our address or ID
  418. if !netAddr.Same(ourAddr) {
  419. if err := sw.addrBook.AddAddress(netAddr, ourAddr); err != nil {
  420. if isPrivateAddr(err) {
  421. sw.Logger.Debug("Won't add peer's address to addrbook", "err", err)
  422. } else {
  423. sw.Logger.Error("Can't add peer's address to addrbook", "err", err)
  424. }
  425. }
  426. }
  427. }
  428. // Persist some peers to disk right away.
  429. // NOTE: integration tests depend on this
  430. sw.addrBook.Save()
  431. }
  432. // permute the list, dial them in random order.
  433. perm := sw.rng.Perm(len(netAddrs))
  434. for i := 0; i < len(perm); i++ {
  435. go func(i int) {
  436. j := perm[i]
  437. addr := netAddrs[j]
  438. if addr.Same(ourAddr) {
  439. sw.Logger.Debug("Ignore attempt to connect to ourselves", "addr", addr, "ourAddr", ourAddr)
  440. return
  441. }
  442. sw.randomSleep(0)
  443. err := sw.DialPeerWithAddress(addr)
  444. if err != nil {
  445. switch err.(type) {
  446. case ErrSwitchConnectToSelf, ErrSwitchDuplicatePeerID, ErrCurrentlyDialingOrExistingAddress:
  447. sw.Logger.Debug("Error dialing peer", "err", err)
  448. default:
  449. sw.Logger.Error("Error dialing peer", "err", err)
  450. }
  451. }
  452. }(i)
  453. }
  454. }
  455. // DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects
  456. // and authenticates successfully.
  457. // If we're currently dialing this address or it belongs to an existing peer,
  458. // ErrCurrentlyDialingOrExistingAddress is returned.
  459. func (sw *Switch) DialPeerWithAddress(addr *NetAddress) error {
  460. if sw.IsDialingOrExistingAddress(addr) {
  461. return ErrCurrentlyDialingOrExistingAddress{addr.String()}
  462. }
  463. sw.dialing.Set(string(addr.ID), addr)
  464. defer sw.dialing.Delete(string(addr.ID))
  465. return sw.addOutboundPeerWithConfig(addr, sw.config)
  466. }
  467. // sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds]
  468. func (sw *Switch) randomSleep(interval time.Duration) {
  469. r := time.Duration(sw.rng.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond
  470. time.Sleep(r + interval)
  471. }
  472. // IsDialingOrExistingAddress returns true if switch has a peer with the given
  473. // address or dialing it at the moment.
  474. func (sw *Switch) IsDialingOrExistingAddress(addr *NetAddress) bool {
  475. return sw.dialing.Has(string(addr.ID)) ||
  476. sw.peers.Has(addr.ID) ||
  477. (!sw.config.AllowDuplicateIP && sw.peers.HasIP(addr.IP))
  478. }
  479. // AddPersistentPeers allows you to set persistent peers. It ignores
  480. // ErrNetAddressLookup. However, if there are other errors, first encounter is
  481. // returned.
  482. func (sw *Switch) AddPersistentPeers(addrs []string) error {
  483. sw.Logger.Info("Adding persistent peers", "addrs", addrs)
  484. netAddrs, errs := NewNetAddressStrings(addrs)
  485. // report all the errors
  486. for _, err := range errs {
  487. sw.Logger.Error("Error in peer's address", "err", err)
  488. }
  489. // return first non-ErrNetAddressLookup error
  490. for _, err := range errs {
  491. if _, ok := err.(ErrNetAddressLookup); ok {
  492. continue
  493. }
  494. return err
  495. }
  496. sw.persistentPeersAddrs = netAddrs
  497. return nil
  498. }
  499. func (sw *Switch) AddUnconditionalPeerIDs(ids []string) error {
  500. sw.Logger.Info("Adding unconditional peer ids", "ids", ids)
  501. for i, id := range ids {
  502. err := validateID(ID(id))
  503. if err != nil {
  504. return fmt.Errorf("wrong ID #%d: %w", i, err)
  505. }
  506. sw.unconditionalPeerIDs[ID(id)] = struct{}{}
  507. }
  508. return nil
  509. }
  510. func (sw *Switch) AddPrivatePeerIDs(ids []string) error {
  511. validIDs := make([]string, 0, len(ids))
  512. for i, id := range ids {
  513. err := validateID(ID(id))
  514. if err != nil {
  515. return fmt.Errorf("wrong ID #%d: %w", i, err)
  516. }
  517. validIDs = append(validIDs, id)
  518. }
  519. sw.addrBook.AddPrivateIDs(validIDs)
  520. return nil
  521. }
  522. func (sw *Switch) IsPeerPersistent(na *NetAddress) bool {
  523. for _, pa := range sw.persistentPeersAddrs {
  524. if pa.Equals(na) {
  525. return true
  526. }
  527. }
  528. return false
  529. }
  530. func (sw *Switch) acceptRoutine() {
  531. for {
  532. p, err := sw.transport.Accept(peerConfig{
  533. chDescs: sw.chDescs,
  534. onPeerError: sw.StopPeerForError,
  535. reactorsByCh: sw.reactorsByCh,
  536. metrics: sw.metrics,
  537. isPersistent: sw.IsPeerPersistent,
  538. })
  539. if err != nil {
  540. switch err := err.(type) {
  541. case ErrRejected:
  542. if err.IsSelf() {
  543. // Remove the given address from the address book and add to our addresses
  544. // to avoid dialing in the future.
  545. addr := err.Addr()
  546. sw.addrBook.RemoveAddress(&addr)
  547. sw.addrBook.AddOurAddress(&addr)
  548. }
  549. sw.Logger.Info(
  550. "Inbound Peer rejected",
  551. "err", err,
  552. "numPeers", sw.peers.Size(),
  553. )
  554. continue
  555. case ErrFilterTimeout:
  556. sw.Logger.Error(
  557. "Peer filter timed out",
  558. "err", err,
  559. )
  560. continue
  561. case ErrTransportClosed:
  562. sw.Logger.Error(
  563. "Stopped accept routine, as transport is closed",
  564. "numPeers", sw.peers.Size(),
  565. )
  566. default:
  567. sw.Logger.Error(
  568. "Accept on transport errored",
  569. "err", err,
  570. "numPeers", sw.peers.Size(),
  571. )
  572. // We could instead have a retry loop around the acceptRoutine,
  573. // but that would need to stop and let the node shutdown eventually.
  574. // So might as well panic and let process managers restart the node.
  575. // There's no point in letting the node run without the acceptRoutine,
  576. // since it won't be able to accept new connections.
  577. panic(fmt.Errorf("accept routine exited: %v", err))
  578. }
  579. break
  580. }
  581. if !sw.IsPeerUnconditional(p.NodeInfo().ID()) {
  582. // Ignore connection if we already have enough peers.
  583. _, in, _ := sw.NumPeers()
  584. if in >= sw.config.MaxNumInboundPeers {
  585. sw.Logger.Info(
  586. "Ignoring inbound connection: already have enough inbound peers",
  587. "address", p.SocketAddr(),
  588. "have", in,
  589. "max", sw.config.MaxNumInboundPeers,
  590. )
  591. sw.transport.Cleanup(p)
  592. continue
  593. }
  594. }
  595. if err := sw.addPeer(p); err != nil {
  596. sw.transport.Cleanup(p)
  597. if p.IsRunning() {
  598. _ = p.Stop()
  599. }
  600. sw.Logger.Info(
  601. "Ignoring inbound connection: error while adding peer",
  602. "err", err,
  603. "id", p.ID(),
  604. )
  605. }
  606. }
  607. }
  608. // dial the peer; make secret connection; authenticate against the dialed ID;
  609. // add the peer.
  610. // if dialing fails, start the reconnect loop. If handshake fails, it's over.
  611. // If peer is started successfully, reconnectLoop will start when
  612. // StopPeerForError is called.
  613. func (sw *Switch) addOutboundPeerWithConfig(
  614. addr *NetAddress,
  615. cfg *config.P2PConfig,
  616. ) error {
  617. sw.Logger.Info("Dialing peer", "address", addr)
  618. // XXX(xla): Remove the leakage of test concerns in implementation.
  619. if cfg.TestDialFail {
  620. go sw.reconnectToPeer(addr)
  621. return fmt.Errorf("dial err (peerConfig.DialFail == true)")
  622. }
  623. p, err := sw.transport.Dial(*addr, peerConfig{
  624. chDescs: sw.chDescs,
  625. onPeerError: sw.StopPeerForError,
  626. isPersistent: sw.IsPeerPersistent,
  627. reactorsByCh: sw.reactorsByCh,
  628. metrics: sw.metrics,
  629. })
  630. if err != nil {
  631. if e, ok := err.(ErrRejected); ok {
  632. if e.IsSelf() {
  633. // Remove the given address from the address book and add to our addresses
  634. // to avoid dialing in the future.
  635. sw.addrBook.RemoveAddress(addr)
  636. sw.addrBook.AddOurAddress(addr)
  637. return err
  638. }
  639. }
  640. // retry persistent peers after
  641. // any dial error besides IsSelf()
  642. if sw.IsPeerPersistent(addr) {
  643. go sw.reconnectToPeer(addr)
  644. }
  645. return err
  646. }
  647. if err := sw.addPeer(p); err != nil {
  648. sw.transport.Cleanup(p)
  649. if p.IsRunning() {
  650. _ = p.Stop()
  651. }
  652. return err
  653. }
  654. return nil
  655. }
  656. func (sw *Switch) filterPeer(p Peer) error {
  657. // Avoid duplicate
  658. if sw.peers.Has(p.ID()) {
  659. return ErrRejected{id: p.ID(), isDuplicate: true}
  660. }
  661. errc := make(chan error, len(sw.peerFilters))
  662. for _, f := range sw.peerFilters {
  663. go func(f PeerFilterFunc, p Peer, errc chan<- error) {
  664. errc <- f(sw.peers, p)
  665. }(f, p, errc)
  666. }
  667. for i := 0; i < cap(errc); i++ {
  668. select {
  669. case err := <-errc:
  670. if err != nil {
  671. return ErrRejected{id: p.ID(), err: err, isFiltered: true}
  672. }
  673. case <-time.After(sw.filterTimeout):
  674. return ErrFilterTimeout{}
  675. }
  676. }
  677. return nil
  678. }
  679. // addPeer starts up the Peer and adds it to the Switch. Error is returned if
  680. // the peer is filtered out or failed to start or can't be added.
  681. func (sw *Switch) addPeer(p Peer) error {
  682. if err := sw.filterPeer(p); err != nil {
  683. return err
  684. }
  685. p.SetLogger(sw.Logger.With("peer", p.SocketAddr()))
  686. // Handle the shut down case where the switch has stopped but we're
  687. // concurrently trying to add a peer.
  688. if !sw.IsRunning() {
  689. // XXX should this return an error or just log and terminate?
  690. sw.Logger.Error("Won't start a peer - switch is not running", "peer", p)
  691. return nil
  692. }
  693. // Add some data to the peer, which is required by reactors.
  694. for _, reactor := range sw.reactors {
  695. p = reactor.InitPeer(p)
  696. }
  697. // Start the peer's send/recv routines.
  698. // Must start it before adding it to the peer set
  699. // to prevent Start and Stop from being called concurrently.
  700. err := p.Start()
  701. if err != nil {
  702. // Should never happen
  703. sw.Logger.Error("Error starting peer", "err", err, "peer", p)
  704. return err
  705. }
  706. // Add the peer to PeerSet. Do this before starting the reactors
  707. // so that if Receive errors, we will find the peer and remove it.
  708. // Add should not err since we already checked peers.Has().
  709. if err := sw.peers.Add(p); err != nil {
  710. return err
  711. }
  712. sw.metrics.Peers.Add(float64(1))
  713. // Start all the reactor protocols on the peer.
  714. for _, reactor := range sw.reactors {
  715. reactor.AddPeer(p)
  716. }
  717. sw.Logger.Info("Added peer", "peer", p)
  718. return nil
  719. }