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.

834 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. sw.Logger.Error("Stopping peer for error", "peer", peer, "err", reason)
  275. sw.stopAndRemovePeer(peer, reason)
  276. if peer.IsPersistent() {
  277. var addr *NetAddress
  278. if peer.IsOutbound() { // socket address for outbound peers
  279. addr = peer.SocketAddr()
  280. } else { // self-reported address for inbound peers
  281. var err error
  282. addr, err = peer.NodeInfo().NetAddress()
  283. if err != nil {
  284. sw.Logger.Error("Wanted to reconnect to inbound peer, but self-reported address is wrong",
  285. "peer", peer, "err", err)
  286. return
  287. }
  288. }
  289. go sw.reconnectToPeer(addr)
  290. }
  291. }
  292. // StopPeerGracefully disconnects from a peer gracefully.
  293. // TODO: handle graceful disconnects.
  294. func (sw *Switch) StopPeerGracefully(peer Peer) {
  295. sw.Logger.Info("Stopping peer gracefully")
  296. sw.stopAndRemovePeer(peer, nil)
  297. }
  298. func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) {
  299. sw.transport.Cleanup(peer)
  300. if err := peer.Stop(); err != nil {
  301. sw.Logger.Error("error while stopping peer", "error", err) // TODO: should return error to be handled accordingly
  302. }
  303. for _, reactor := range sw.reactors {
  304. reactor.RemovePeer(peer, reason)
  305. }
  306. // Removing a peer should go last to avoid a situation where a peer
  307. // reconnect to our node and the switch calls InitPeer before
  308. // RemovePeer is finished.
  309. // https://github.com/tendermint/tendermint/issues/3338
  310. if sw.peers.Remove(peer) {
  311. sw.metrics.Peers.Add(float64(-1))
  312. }
  313. }
  314. // reconnectToPeer tries to reconnect to the addr, first repeatedly
  315. // with a fixed interval, then with exponential backoff.
  316. // If no success after all that, it stops trying, and leaves it
  317. // to the PEX/Addrbook to find the peer with the addr again
  318. // NOTE: this will keep trying even if the handshake or auth fails.
  319. // TODO: be more explicit with error types so we only retry on certain failures
  320. // - ie. if we're getting ErrDuplicatePeer we can stop
  321. // because the addrbook got us the peer back already
  322. func (sw *Switch) reconnectToPeer(addr *NetAddress) {
  323. if sw.reconnecting.Has(string(addr.ID)) {
  324. return
  325. }
  326. sw.reconnecting.Set(string(addr.ID), addr)
  327. defer sw.reconnecting.Delete(string(addr.ID))
  328. start := time.Now()
  329. sw.Logger.Info("Reconnecting to peer", "addr", addr)
  330. for i := 0; i < reconnectAttempts; i++ {
  331. if !sw.IsRunning() {
  332. return
  333. }
  334. err := sw.DialPeerWithAddress(addr)
  335. if err == nil {
  336. return // success
  337. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  338. return
  339. }
  340. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  341. // sleep a set amount
  342. sw.randomSleep(reconnectInterval)
  343. continue
  344. }
  345. sw.Logger.Error("Failed to reconnect to peer. Beginning exponential backoff",
  346. "addr", addr, "elapsed", time.Since(start))
  347. for i := 0; i < reconnectBackOffAttempts; i++ {
  348. if !sw.IsRunning() {
  349. return
  350. }
  351. // sleep an exponentially increasing amount
  352. sleepIntervalSeconds := math.Pow(reconnectBackOffBaseSeconds, float64(i))
  353. sw.randomSleep(time.Duration(sleepIntervalSeconds) * time.Second)
  354. err := sw.DialPeerWithAddress(addr)
  355. if err == nil {
  356. return // success
  357. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  358. return
  359. }
  360. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  361. }
  362. sw.Logger.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start))
  363. }
  364. // SetAddrBook allows to set address book on Switch.
  365. func (sw *Switch) SetAddrBook(addrBook AddrBook) {
  366. sw.addrBook = addrBook
  367. }
  368. // MarkPeerAsGood marks the given peer as good when it did something useful
  369. // like contributed to consensus.
  370. func (sw *Switch) MarkPeerAsGood(peer Peer) {
  371. if sw.addrBook != nil {
  372. sw.addrBook.MarkGood(peer.ID())
  373. }
  374. }
  375. //---------------------------------------------------------------------
  376. // Dialing
  377. type privateAddr interface {
  378. PrivateAddr() bool
  379. }
  380. func isPrivateAddr(err error) bool {
  381. te, ok := err.(privateAddr)
  382. return ok && te.PrivateAddr()
  383. }
  384. // DialPeersAsync dials a list of peers asynchronously in random order.
  385. // Used to dial peers from config on startup or from unsafe-RPC (trusted sources).
  386. // It ignores ErrNetAddressLookup. However, if there are other errors, first
  387. // encounter is returned.
  388. // Nop if there are no peers.
  389. func (sw *Switch) DialPeersAsync(peers []string) error {
  390. netAddrs, errs := NewNetAddressStrings(peers)
  391. // report all the errors
  392. for _, err := range errs {
  393. sw.Logger.Error("Error in peer's address", "err", err)
  394. }
  395. // return first non-ErrNetAddressLookup error
  396. for _, err := range errs {
  397. if _, ok := err.(ErrNetAddressLookup); ok {
  398. continue
  399. }
  400. return err
  401. }
  402. sw.dialPeersAsync(netAddrs)
  403. return nil
  404. }
  405. func (sw *Switch) dialPeersAsync(netAddrs []*NetAddress) {
  406. ourAddr := sw.NetAddress()
  407. // TODO: this code feels like it's in the wrong place.
  408. // The integration tests depend on the addrBook being saved
  409. // right away but maybe we can change that. Recall that
  410. // the addrBook is only written to disk every 2min
  411. if sw.addrBook != nil {
  412. // add peers to `addrBook`
  413. for _, netAddr := range netAddrs {
  414. // do not add our address or ID
  415. if !netAddr.Same(ourAddr) {
  416. if err := sw.addrBook.AddAddress(netAddr, ourAddr); err != nil {
  417. if isPrivateAddr(err) {
  418. sw.Logger.Debug("Won't add peer's address to addrbook", "err", err)
  419. } else {
  420. sw.Logger.Error("Can't add peer's address to addrbook", "err", err)
  421. }
  422. }
  423. }
  424. }
  425. // Persist some peers to disk right away.
  426. // NOTE: integration tests depend on this
  427. sw.addrBook.Save()
  428. }
  429. // permute the list, dial them in random order.
  430. perm := sw.rng.Perm(len(netAddrs))
  431. for i := 0; i < len(perm); i++ {
  432. go func(i int) {
  433. j := perm[i]
  434. addr := netAddrs[j]
  435. if addr.Same(ourAddr) {
  436. sw.Logger.Debug("Ignore attempt to connect to ourselves", "addr", addr, "ourAddr", ourAddr)
  437. return
  438. }
  439. sw.randomSleep(0)
  440. err := sw.DialPeerWithAddress(addr)
  441. if err != nil {
  442. switch err.(type) {
  443. case ErrSwitchConnectToSelf, ErrSwitchDuplicatePeerID, ErrCurrentlyDialingOrExistingAddress:
  444. sw.Logger.Debug("Error dialing peer", "err", err)
  445. default:
  446. sw.Logger.Error("Error dialing peer", "err", err)
  447. }
  448. }
  449. }(i)
  450. }
  451. }
  452. // DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects
  453. // and authenticates successfully.
  454. // If we're currently dialing this address or it belongs to an existing peer,
  455. // ErrCurrentlyDialingOrExistingAddress is returned.
  456. func (sw *Switch) DialPeerWithAddress(addr *NetAddress) error {
  457. if sw.IsDialingOrExistingAddress(addr) {
  458. return ErrCurrentlyDialingOrExistingAddress{addr.String()}
  459. }
  460. sw.dialing.Set(string(addr.ID), addr)
  461. defer sw.dialing.Delete(string(addr.ID))
  462. return sw.addOutboundPeerWithConfig(addr, sw.config)
  463. }
  464. // sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds]
  465. func (sw *Switch) randomSleep(interval time.Duration) {
  466. r := time.Duration(sw.rng.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond
  467. time.Sleep(r + interval)
  468. }
  469. // IsDialingOrExistingAddress returns true if switch has a peer with the given
  470. // address or dialing it at the moment.
  471. func (sw *Switch) IsDialingOrExistingAddress(addr *NetAddress) bool {
  472. return sw.dialing.Has(string(addr.ID)) ||
  473. sw.peers.Has(addr.ID) ||
  474. (!sw.config.AllowDuplicateIP && sw.peers.HasIP(addr.IP))
  475. }
  476. // AddPersistentPeers allows you to set persistent peers. It ignores
  477. // ErrNetAddressLookup. However, if there are other errors, first encounter is
  478. // returned.
  479. func (sw *Switch) AddPersistentPeers(addrs []string) error {
  480. sw.Logger.Info("Adding persistent peers", "addrs", addrs)
  481. netAddrs, errs := NewNetAddressStrings(addrs)
  482. // report all the errors
  483. for _, err := range errs {
  484. sw.Logger.Error("Error in peer's address", "err", err)
  485. }
  486. // return first non-ErrNetAddressLookup error
  487. for _, err := range errs {
  488. if _, ok := err.(ErrNetAddressLookup); ok {
  489. continue
  490. }
  491. return err
  492. }
  493. sw.persistentPeersAddrs = netAddrs
  494. return nil
  495. }
  496. func (sw *Switch) AddUnconditionalPeerIDs(ids []string) error {
  497. sw.Logger.Info("Adding unconditional peer ids", "ids", ids)
  498. for i, id := range ids {
  499. err := validateID(ID(id))
  500. if err != nil {
  501. return fmt.Errorf("wrong ID #%d: %w", i, err)
  502. }
  503. sw.unconditionalPeerIDs[ID(id)] = struct{}{}
  504. }
  505. return nil
  506. }
  507. func (sw *Switch) AddPrivatePeerIDs(ids []string) error {
  508. validIDs := make([]string, 0, len(ids))
  509. for i, id := range ids {
  510. err := validateID(ID(id))
  511. if err != nil {
  512. return fmt.Errorf("wrong ID #%d: %w", i, err)
  513. }
  514. validIDs = append(validIDs, id)
  515. }
  516. sw.addrBook.AddPrivateIDs(validIDs)
  517. return nil
  518. }
  519. func (sw *Switch) IsPeerPersistent(na *NetAddress) bool {
  520. for _, pa := range sw.persistentPeersAddrs {
  521. if pa.Equals(na) {
  522. return true
  523. }
  524. }
  525. return false
  526. }
  527. func (sw *Switch) acceptRoutine() {
  528. for {
  529. p, err := sw.transport.Accept(peerConfig{
  530. chDescs: sw.chDescs,
  531. onPeerError: sw.StopPeerForError,
  532. reactorsByCh: sw.reactorsByCh,
  533. metrics: sw.metrics,
  534. isPersistent: sw.IsPeerPersistent,
  535. })
  536. if err != nil {
  537. switch err := err.(type) {
  538. case ErrRejected:
  539. if err.IsSelf() {
  540. // Remove the given address from the address book and add to our addresses
  541. // to avoid dialing in the future.
  542. addr := err.Addr()
  543. sw.addrBook.RemoveAddress(&addr)
  544. sw.addrBook.AddOurAddress(&addr)
  545. }
  546. sw.Logger.Info(
  547. "Inbound Peer rejected",
  548. "err", err,
  549. "numPeers", sw.peers.Size(),
  550. )
  551. continue
  552. case ErrFilterTimeout:
  553. sw.Logger.Error(
  554. "Peer filter timed out",
  555. "err", err,
  556. )
  557. continue
  558. case ErrTransportClosed:
  559. sw.Logger.Error(
  560. "Stopped accept routine, as transport is closed",
  561. "numPeers", sw.peers.Size(),
  562. )
  563. default:
  564. sw.Logger.Error(
  565. "Accept on transport errored",
  566. "err", err,
  567. "numPeers", sw.peers.Size(),
  568. )
  569. // We could instead have a retry loop around the acceptRoutine,
  570. // but that would need to stop and let the node shutdown eventually.
  571. // So might as well panic and let process managers restart the node.
  572. // There's no point in letting the node run without the acceptRoutine,
  573. // since it won't be able to accept new connections.
  574. panic(fmt.Errorf("accept routine exited: %v", err))
  575. }
  576. break
  577. }
  578. if !sw.IsPeerUnconditional(p.NodeInfo().ID()) {
  579. // Ignore connection if we already have enough peers.
  580. _, in, _ := sw.NumPeers()
  581. if in >= sw.config.MaxNumInboundPeers {
  582. sw.Logger.Info(
  583. "Ignoring inbound connection: already have enough inbound peers",
  584. "address", p.SocketAddr(),
  585. "have", in,
  586. "max", sw.config.MaxNumInboundPeers,
  587. )
  588. sw.transport.Cleanup(p)
  589. continue
  590. }
  591. }
  592. if err := sw.addPeer(p); err != nil {
  593. sw.transport.Cleanup(p)
  594. if p.IsRunning() {
  595. _ = p.Stop()
  596. }
  597. sw.Logger.Info(
  598. "Ignoring inbound connection: error while adding peer",
  599. "err", err,
  600. "id", p.ID(),
  601. )
  602. }
  603. }
  604. }
  605. // dial the peer; make secret connection; authenticate against the dialed ID;
  606. // add the peer.
  607. // if dialing fails, start the reconnect loop. If handshake fails, it's over.
  608. // If peer is started successfully, reconnectLoop will start when
  609. // StopPeerForError is called.
  610. func (sw *Switch) addOutboundPeerWithConfig(
  611. addr *NetAddress,
  612. cfg *config.P2PConfig,
  613. ) error {
  614. sw.Logger.Info("Dialing peer", "address", addr)
  615. // XXX(xla): Remove the leakage of test concerns in implementation.
  616. if cfg.TestDialFail {
  617. go sw.reconnectToPeer(addr)
  618. return fmt.Errorf("dial err (peerConfig.DialFail == true)")
  619. }
  620. p, err := sw.transport.Dial(*addr, peerConfig{
  621. chDescs: sw.chDescs,
  622. onPeerError: sw.StopPeerForError,
  623. isPersistent: sw.IsPeerPersistent,
  624. reactorsByCh: sw.reactorsByCh,
  625. metrics: sw.metrics,
  626. })
  627. if err != nil {
  628. if e, ok := err.(ErrRejected); ok {
  629. if e.IsSelf() {
  630. // Remove the given address from the address book and add to our addresses
  631. // to avoid dialing in the future.
  632. sw.addrBook.RemoveAddress(addr)
  633. sw.addrBook.AddOurAddress(addr)
  634. return err
  635. }
  636. }
  637. // retry persistent peers after
  638. // any dial error besides IsSelf()
  639. if sw.IsPeerPersistent(addr) {
  640. go sw.reconnectToPeer(addr)
  641. }
  642. return err
  643. }
  644. if err := sw.addPeer(p); err != nil {
  645. sw.transport.Cleanup(p)
  646. if p.IsRunning() {
  647. _ = p.Stop()
  648. }
  649. return err
  650. }
  651. return nil
  652. }
  653. func (sw *Switch) filterPeer(p Peer) error {
  654. // Avoid duplicate
  655. if sw.peers.Has(p.ID()) {
  656. return ErrRejected{id: p.ID(), isDuplicate: true}
  657. }
  658. errc := make(chan error, len(sw.peerFilters))
  659. for _, f := range sw.peerFilters {
  660. go func(f PeerFilterFunc, p Peer, errc chan<- error) {
  661. errc <- f(sw.peers, p)
  662. }(f, p, errc)
  663. }
  664. for i := 0; i < cap(errc); i++ {
  665. select {
  666. case err := <-errc:
  667. if err != nil {
  668. return ErrRejected{id: p.ID(), err: err, isFiltered: true}
  669. }
  670. case <-time.After(sw.filterTimeout):
  671. return ErrFilterTimeout{}
  672. }
  673. }
  674. return nil
  675. }
  676. // addPeer starts up the Peer and adds it to the Switch. Error is returned if
  677. // the peer is filtered out or failed to start or can't be added.
  678. func (sw *Switch) addPeer(p Peer) error {
  679. if err := sw.filterPeer(p); err != nil {
  680. return err
  681. }
  682. p.SetLogger(sw.Logger.With("peer", p.SocketAddr()))
  683. // Handle the shut down case where the switch has stopped but we're
  684. // concurrently trying to add a peer.
  685. if !sw.IsRunning() {
  686. // XXX should this return an error or just log and terminate?
  687. sw.Logger.Error("Won't start a peer - switch is not running", "peer", p)
  688. return nil
  689. }
  690. // Add some data to the peer, which is required by reactors.
  691. for _, reactor := range sw.reactors {
  692. p = reactor.InitPeer(p)
  693. }
  694. // Start the peer's send/recv routines.
  695. // Must start it before adding it to the peer set
  696. // to prevent Start and Stop from being called concurrently.
  697. err := p.Start()
  698. if err != nil {
  699. // Should never happen
  700. sw.Logger.Error("Error starting peer", "err", err, "peer", p)
  701. return err
  702. }
  703. // Add the peer to PeerSet. Do this before starting the reactors
  704. // so that if Receive errors, we will find the peer and remove it.
  705. // Add should not err since we already checked peers.Has().
  706. if err := sw.peers.Add(p); err != nil {
  707. return err
  708. }
  709. sw.metrics.Peers.Add(float64(1))
  710. // Start all the reactor protocols on the peer.
  711. for _, reactor := range sw.reactors {
  712. reactor.AddPeer(p)
  713. }
  714. sw.Logger.Info("Added peer", "peer", p)
  715. return nil
  716. }