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.

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