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.

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