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.

820 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/pkg/errors"
  8. "github.com/tendermint/tendermint/config"
  9. "github.com/tendermint/tendermint/libs/cmap"
  10. "github.com/tendermint/tendermint/libs/rand"
  11. "github.com/tendermint/tendermint/libs/service"
  12. "github.com/tendermint/tendermint/p2p/conn"
  13. )
  14. const (
  15. // wait a random amount of time from this interval
  16. // before dialing peers or reconnecting to help prevent DoS
  17. dialRandomizerIntervalMilliseconds = 3000
  18. // repeatedly try to reconnect for a few minutes
  19. // ie. 5 * 20 = 100s
  20. reconnectAttempts = 20
  21. reconnectInterval = 5 * time.Second
  22. // then move into exponential backoff mode for ~1day
  23. // ie. 3**10 = 16hrs
  24. reconnectBackOffAttempts = 10
  25. reconnectBackOffBaseSeconds = 3
  26. )
  27. // MConnConfig returns an MConnConfig with fields updated
  28. // from the P2PConfig.
  29. func MConnConfig(cfg *config.P2PConfig) conn.MConnConfig {
  30. mConfig := conn.DefaultMConnConfig()
  31. mConfig.FlushThrottle = cfg.FlushThrottleTimeout
  32. mConfig.SendRate = cfg.SendRate
  33. mConfig.RecvRate = cfg.RecvRate
  34. mConfig.MaxPacketMsgPayloadSize = cfg.MaxPacketMsgPayloadSize
  35. return mConfig
  36. }
  37. //-----------------------------------------------------------------------------
  38. // An AddrBook represents an address book from the pex package, which is used
  39. // to store peer addresses.
  40. type AddrBook interface {
  41. AddAddress(addr *NetAddress, src *NetAddress) error
  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 errors.Wrapf(err, "failed to start %v", reactor)
  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 := errors.Cause(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 errors.Wrapf(err, "wrong ID #%d", i)
  498. }
  499. sw.unconditionalPeerIDs[ID(id)] = struct{}{}
  500. }
  501. return nil
  502. }
  503. func (sw *Switch) isPeerPersistentFn() func(*NetAddress) bool {
  504. return sw.IsPeerPersistent
  505. }
  506. func (sw *Switch) IsPeerPersistent(na *NetAddress) bool {
  507. for _, pa := range sw.persistentPeersAddrs {
  508. if pa.Equals(na) {
  509. return true
  510. }
  511. }
  512. return false
  513. }
  514. func (sw *Switch) acceptRoutine() {
  515. for {
  516. p, err := sw.transport.Accept(peerConfig{
  517. chDescs: sw.chDescs,
  518. onPeerError: sw.StopPeerForError,
  519. reactorsByCh: sw.reactorsByCh,
  520. metrics: sw.metrics,
  521. isPersistent: sw.IsPeerPersistent,
  522. })
  523. if err != nil {
  524. switch err := err.(type) {
  525. case ErrRejected:
  526. if err.IsSelf() {
  527. // Remove the given address from the address book and add to our addresses
  528. // to avoid dialing in the future.
  529. addr := err.Addr()
  530. sw.addrBook.RemoveAddress(&addr)
  531. sw.addrBook.AddOurAddress(&addr)
  532. }
  533. sw.Logger.Info(
  534. "Inbound Peer rejected",
  535. "err", err,
  536. "numPeers", sw.peers.Size(),
  537. )
  538. continue
  539. case ErrFilterTimeout:
  540. sw.Logger.Error(
  541. "Peer filter timed out",
  542. "err", err,
  543. )
  544. continue
  545. case ErrTransportClosed:
  546. sw.Logger.Error(
  547. "Stopped accept routine, as transport is closed",
  548. "numPeers", sw.peers.Size(),
  549. )
  550. default:
  551. sw.Logger.Error(
  552. "Accept on transport errored",
  553. "err", err,
  554. "numPeers", sw.peers.Size(),
  555. )
  556. // We could instead have a retry loop around the acceptRoutine,
  557. // but that would need to stop and let the node shutdown eventually.
  558. // So might as well panic and let process managers restart the node.
  559. // There's no point in letting the node run without the acceptRoutine,
  560. // since it won't be able to accept new connections.
  561. panic(fmt.Errorf("accept routine exited: %v", err))
  562. }
  563. break
  564. }
  565. if !sw.IsPeerUnconditional(p.NodeInfo().ID()) {
  566. // Ignore connection if we already have enough peers.
  567. _, in, _ := sw.NumPeers()
  568. if in >= sw.config.MaxNumInboundPeers {
  569. sw.Logger.Info(
  570. "Ignoring inbound connection: already have enough inbound peers",
  571. "address", p.SocketAddr(),
  572. "have", in,
  573. "max", sw.config.MaxNumInboundPeers,
  574. )
  575. sw.transport.Cleanup(p)
  576. continue
  577. }
  578. }
  579. if err := sw.addPeer(p); err != nil {
  580. sw.transport.Cleanup(p)
  581. if p.IsRunning() {
  582. _ = p.Stop()
  583. }
  584. sw.Logger.Info(
  585. "Ignoring inbound connection: error while adding peer",
  586. "err", err,
  587. "id", p.ID(),
  588. )
  589. }
  590. }
  591. }
  592. // dial the peer; make secret connection; authenticate against the dialed ID;
  593. // add the peer.
  594. // if dialing fails, start the reconnect loop. If handshake fails, it's over.
  595. // If peer is started successfully, reconnectLoop will start when
  596. // StopPeerForError is called.
  597. func (sw *Switch) addOutboundPeerWithConfig(
  598. addr *NetAddress,
  599. cfg *config.P2PConfig,
  600. ) error {
  601. sw.Logger.Info("Dialing peer", "address", addr)
  602. // XXX(xla): Remove the leakage of test concerns in implementation.
  603. if cfg.TestDialFail {
  604. go sw.reconnectToPeer(addr)
  605. return fmt.Errorf("dial err (peerConfig.DialFail == true)")
  606. }
  607. p, err := sw.transport.Dial(*addr, peerConfig{
  608. chDescs: sw.chDescs,
  609. onPeerError: sw.StopPeerForError,
  610. isPersistent: sw.IsPeerPersistent,
  611. reactorsByCh: sw.reactorsByCh,
  612. metrics: sw.metrics,
  613. })
  614. if err != nil {
  615. if e, ok := err.(ErrRejected); ok {
  616. if e.IsSelf() {
  617. // Remove the given address from the address book and add to our addresses
  618. // to avoid dialing in the future.
  619. sw.addrBook.RemoveAddress(addr)
  620. sw.addrBook.AddOurAddress(addr)
  621. return err
  622. }
  623. }
  624. // retry persistent peers after
  625. // any dial error besides IsSelf()
  626. if sw.IsPeerPersistent(addr) {
  627. go sw.reconnectToPeer(addr)
  628. }
  629. return err
  630. }
  631. if err := sw.addPeer(p); err != nil {
  632. sw.transport.Cleanup(p)
  633. if p.IsRunning() {
  634. _ = p.Stop()
  635. }
  636. return err
  637. }
  638. return nil
  639. }
  640. func (sw *Switch) filterPeer(p Peer) error {
  641. // Avoid duplicate
  642. if sw.peers.Has(p.ID()) {
  643. return ErrRejected{id: p.ID(), isDuplicate: true}
  644. }
  645. errc := make(chan error, len(sw.peerFilters))
  646. for _, f := range sw.peerFilters {
  647. go func(f PeerFilterFunc, p Peer, errc chan<- error) {
  648. errc <- f(sw.peers, p)
  649. }(f, p, errc)
  650. }
  651. for i := 0; i < cap(errc); i++ {
  652. select {
  653. case err := <-errc:
  654. if err != nil {
  655. return ErrRejected{id: p.ID(), err: err, isFiltered: true}
  656. }
  657. case <-time.After(sw.filterTimeout):
  658. return ErrFilterTimeout{}
  659. }
  660. }
  661. return nil
  662. }
  663. // addPeer starts up the Peer and adds it to the Switch. Error is returned if
  664. // the peer is filtered out or failed to start or can't be added.
  665. func (sw *Switch) addPeer(p Peer) error {
  666. if err := sw.filterPeer(p); err != nil {
  667. return err
  668. }
  669. p.SetLogger(sw.Logger.With("peer", p.SocketAddr()))
  670. // Handle the shut down case where the switch has stopped but we're
  671. // concurrently trying to add a peer.
  672. if !sw.IsRunning() {
  673. // XXX should this return an error or just log and terminate?
  674. sw.Logger.Error("Won't start a peer - switch is not running", "peer", p)
  675. return nil
  676. }
  677. // Add some data to the peer, which is required by reactors.
  678. for _, reactor := range sw.reactors {
  679. p = reactor.InitPeer(p)
  680. }
  681. // Start the peer's send/recv routines.
  682. // Must start it before adding it to the peer set
  683. // to prevent Start and Stop from being called concurrently.
  684. err := p.Start()
  685. if err != nil {
  686. // Should never happen
  687. sw.Logger.Error("Error starting peer", "err", err, "peer", p)
  688. return err
  689. }
  690. // Add the peer to PeerSet. Do this before starting the reactors
  691. // so that if Receive errors, we will find the peer and remove it.
  692. // Add should not err since we already checked peers.Has().
  693. if err := sw.peers.Add(p); err != nil {
  694. return err
  695. }
  696. sw.metrics.Peers.Add(float64(1))
  697. // Start all the reactor protocols on the peer.
  698. for _, reactor := range sw.reactors {
  699. reactor.AddPeer(p)
  700. }
  701. sw.Logger.Info("Added peer", "peer", p)
  702. return nil
  703. }