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.

830 lines
23 KiB

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