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. cmn "github.com/tendermint/tendermint/libs/common"
  10. "github.com/tendermint/tendermint/p2p/conn"
  11. )
  12. const (
  13. // wait a random amount of time from this interval
  14. // before dialing peers or reconnecting to help prevent DoS
  15. dialRandomizerIntervalMilliseconds = 3000
  16. // repeatedly try to reconnect for a few minutes
  17. // ie. 5 * 20 = 100s
  18. reconnectAttempts = 20
  19. reconnectInterval = 5 * time.Second
  20. // then move into exponential backoff mode for ~1day
  21. // ie. 3**10 = 16hrs
  22. reconnectBackOffAttempts = 10
  23. reconnectBackOffBaseSeconds = 3
  24. )
  25. // MConnConfig returns an MConnConfig with fields updated
  26. // from the P2PConfig.
  27. func MConnConfig(cfg *config.P2PConfig) conn.MConnConfig {
  28. mConfig := conn.DefaultMConnConfig()
  29. mConfig.FlushThrottle = cfg.FlushThrottleTimeout
  30. mConfig.SendRate = cfg.SendRate
  31. mConfig.RecvRate = cfg.RecvRate
  32. mConfig.MaxPacketMsgPayloadSize = cfg.MaxPacketMsgPayloadSize
  33. return mConfig
  34. }
  35. //-----------------------------------------------------------------------------
  36. // An AddrBook represents an address book from the pex package, which is used
  37. // to store peer addresses.
  38. type AddrBook interface {
  39. AddAddress(addr *NetAddress, src *NetAddress) error
  40. AddOurAddress(*NetAddress)
  41. OurAddress(*NetAddress) bool
  42. MarkGood(ID)
  43. RemoveAddress(*NetAddress)
  44. HasAddress(*NetAddress) bool
  45. Save()
  46. }
  47. // PeerFilterFunc to be implemented by filter hooks after a new Peer has been
  48. // fully setup.
  49. type PeerFilterFunc func(IPeerSet, Peer) error
  50. //-----------------------------------------------------------------------------
  51. // Switch handles peer connections and exposes an API to receive incoming messages
  52. // on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one
  53. // or more `Channels`. So while sending outgoing messages is typically performed on the peer,
  54. // incoming messages are received on the reactor.
  55. type Switch struct {
  56. cmn.BaseService
  57. config *config.P2PConfig
  58. reactors map[string]Reactor
  59. chDescs []*conn.ChannelDescriptor
  60. reactorsByCh map[byte]Reactor
  61. peers *PeerSet
  62. dialing *cmn.CMap
  63. reconnecting *cmn.CMap
  64. nodeInfo NodeInfo // our node info
  65. nodeKey *NodeKey // our node privkey
  66. addrBook AddrBook
  67. // peers addresses with whom we'll maintain constant connection
  68. persistentPeersAddrs []*NetAddress
  69. unconditionalPeerIDs map[ID]struct{}
  70. transport Transport
  71. filterTimeout time.Duration
  72. peerFilters []PeerFilterFunc
  73. rng *cmn.Rand // seed for randomizing dial times and orders
  74. metrics *Metrics
  75. }
  76. // NetAddress returns the address the switch is listening on.
  77. func (sw *Switch) NetAddress() *NetAddress {
  78. addr := sw.transport.NetAddress()
  79. return &addr
  80. }
  81. // SwitchOption sets an optional parameter on the Switch.
  82. type SwitchOption func(*Switch)
  83. // NewSwitch creates a new Switch with the given config.
  84. func NewSwitch(
  85. cfg *config.P2PConfig,
  86. transport Transport,
  87. options ...SwitchOption,
  88. ) *Switch {
  89. sw := &Switch{
  90. config: cfg,
  91. reactors: make(map[string]Reactor),
  92. chDescs: make([]*conn.ChannelDescriptor, 0),
  93. reactorsByCh: make(map[byte]Reactor),
  94. peers: NewPeerSet(),
  95. dialing: cmn.NewCMap(),
  96. reconnecting: cmn.NewCMap(),
  97. metrics: NopMetrics(),
  98. transport: transport,
  99. filterTimeout: defaultFilterTimeout,
  100. persistentPeersAddrs: make([]*NetAddress, 0),
  101. unconditionalPeerIDs: make(map[ID]struct{}),
  102. }
  103. // Ensure we have a completely undeterministic PRNG.
  104. sw.rng = cmn.NewRand()
  105. sw.BaseService = *cmn.NewBaseService(nil, "P2P Switch", sw)
  106. for _, option := range options {
  107. option(sw)
  108. }
  109. return sw
  110. }
  111. // SwitchFilterTimeout sets the timeout used for peer filters.
  112. func SwitchFilterTimeout(timeout time.Duration) SwitchOption {
  113. return func(sw *Switch) { sw.filterTimeout = timeout }
  114. }
  115. // SwitchPeerFilters sets the filters for rejection of new peers.
  116. func SwitchPeerFilters(filters ...PeerFilterFunc) SwitchOption {
  117. return func(sw *Switch) { sw.peerFilters = filters }
  118. }
  119. // WithMetrics sets the metrics.
  120. func WithMetrics(metrics *Metrics) SwitchOption {
  121. return func(sw *Switch) { sw.metrics = metrics }
  122. }
  123. //---------------------------------------------------------------------
  124. // Switch setup
  125. // AddReactor adds the given reactor to the switch.
  126. // NOTE: Not goroutine safe.
  127. func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor {
  128. for _, chDesc := range reactor.GetChannels() {
  129. chID := chDesc.ID
  130. // No two reactors can share the same channel.
  131. if sw.reactorsByCh[chID] != nil {
  132. panic(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor))
  133. }
  134. sw.chDescs = append(sw.chDescs, chDesc)
  135. sw.reactorsByCh[chID] = reactor
  136. }
  137. sw.reactors[name] = reactor
  138. reactor.SetSwitch(sw)
  139. return reactor
  140. }
  141. // RemoveReactor removes the given Reactor from the Switch.
  142. // NOTE: Not goroutine safe.
  143. func (sw *Switch) RemoveReactor(name string, reactor Reactor) {
  144. for _, chDesc := range reactor.GetChannels() {
  145. // remove channel description
  146. for i := 0; i < len(sw.chDescs); i++ {
  147. if chDesc.ID == sw.chDescs[i].ID {
  148. sw.chDescs = append(sw.chDescs[:i], sw.chDescs[i+1:]...)
  149. break
  150. }
  151. }
  152. delete(sw.reactorsByCh, chDesc.ID)
  153. }
  154. delete(sw.reactors, name)
  155. reactor.SetSwitch(nil)
  156. }
  157. // Reactors returns a map of reactors registered on the switch.
  158. // NOTE: Not goroutine safe.
  159. func (sw *Switch) Reactors() map[string]Reactor {
  160. return sw.reactors
  161. }
  162. // Reactor returns the reactor with the given name.
  163. // NOTE: Not goroutine safe.
  164. func (sw *Switch) Reactor(name string) Reactor {
  165. return sw.reactors[name]
  166. }
  167. // SetNodeInfo sets the switch's NodeInfo for checking compatibility and handshaking with other nodes.
  168. // NOTE: Not goroutine safe.
  169. func (sw *Switch) SetNodeInfo(nodeInfo NodeInfo) {
  170. sw.nodeInfo = nodeInfo
  171. }
  172. // NodeInfo returns the switch's NodeInfo.
  173. // NOTE: Not goroutine safe.
  174. func (sw *Switch) NodeInfo() NodeInfo {
  175. return sw.nodeInfo
  176. }
  177. // SetNodeKey sets the switch's private key for authenticated encryption.
  178. // NOTE: Not goroutine safe.
  179. func (sw *Switch) SetNodeKey(nodeKey *NodeKey) {
  180. sw.nodeKey = nodeKey
  181. }
  182. //---------------------------------------------------------------------
  183. // Service start/stop
  184. // OnStart implements BaseService. It starts all the reactors and peers.
  185. func (sw *Switch) OnStart() error {
  186. // Start reactors
  187. for _, reactor := range sw.reactors {
  188. err := reactor.Start()
  189. if err != nil {
  190. return errors.Wrapf(err, "failed to start %v", reactor)
  191. }
  192. }
  193. // Start accepting Peers.
  194. go sw.acceptRoutine()
  195. return nil
  196. }
  197. // OnStop implements BaseService. It stops all peers and reactors.
  198. func (sw *Switch) OnStop() {
  199. // Stop peers
  200. for _, p := range sw.peers.List() {
  201. sw.stopAndRemovePeer(p, nil)
  202. }
  203. // Stop reactors
  204. sw.Logger.Debug("Switch: Stopping reactors")
  205. for _, reactor := range sw.reactors {
  206. reactor.Stop()
  207. }
  208. }
  209. //---------------------------------------------------------------------
  210. // Peers
  211. // Broadcast runs a go routine for each attempted send, which will block trying
  212. // to send for defaultSendTimeoutSeconds. Returns a channel which receives
  213. // success values for each attempted send (false if times out). Channel will be
  214. // closed once msg bytes are sent to all peers (or time out).
  215. //
  216. // NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved.
  217. func (sw *Switch) Broadcast(chID byte, msgBytes []byte) chan bool {
  218. sw.Logger.Debug("Broadcast", "channel", chID, "msgBytes", fmt.Sprintf("%X", msgBytes))
  219. peers := sw.peers.List()
  220. var wg sync.WaitGroup
  221. wg.Add(len(peers))
  222. successChan := make(chan bool, len(peers))
  223. for _, peer := range peers {
  224. go func(p Peer) {
  225. defer wg.Done()
  226. success := p.Send(chID, msgBytes)
  227. successChan <- success
  228. }(peer)
  229. }
  230. go func() {
  231. wg.Wait()
  232. close(successChan)
  233. }()
  234. return successChan
  235. }
  236. // NumPeers returns the count of outbound/inbound and outbound-dialing peers.
  237. // unconditional peers are not counted here.
  238. func (sw *Switch) NumPeers() (outbound, inbound, dialing int) {
  239. peers := sw.peers.List()
  240. for _, peer := range peers {
  241. if peer.IsOutbound() {
  242. if !sw.IsPeerUnconditional(peer.ID()) {
  243. outbound++
  244. }
  245. } else {
  246. if !sw.IsPeerUnconditional(peer.ID()) {
  247. inbound++
  248. }
  249. }
  250. }
  251. dialing = sw.dialing.Size()
  252. return
  253. }
  254. func (sw *Switch) IsPeerUnconditional(id ID) bool {
  255. _, ok := sw.unconditionalPeerIDs[id]
  256. return ok
  257. }
  258. // MaxNumOutboundPeers returns a maximum number of outbound peers.
  259. func (sw *Switch) MaxNumOutboundPeers() int {
  260. return sw.config.MaxNumOutboundPeers
  261. }
  262. // Peers returns the set of peers that are connected to the switch.
  263. func (sw *Switch) Peers() IPeerSet {
  264. return sw.peers
  265. }
  266. // StopPeerForError disconnects from a peer due to external error.
  267. // If the peer is persistent, it will attempt to reconnect.
  268. // TODO: make record depending on reason.
  269. func (sw *Switch) StopPeerForError(peer Peer, reason interface{}) {
  270. sw.Logger.Error("Stopping peer for error", "peer", peer, "err", reason)
  271. sw.stopAndRemovePeer(peer, reason)
  272. if peer.IsPersistent() {
  273. var addr *NetAddress
  274. if peer.IsOutbound() { // socket address for outbound peers
  275. addr = peer.SocketAddr()
  276. } else { // self-reported address for inbound peers
  277. var err error
  278. addr, err = peer.NodeInfo().NetAddress()
  279. if err != nil {
  280. sw.Logger.Error("Wanted to reconnect to inbound peer, but self-reported address is wrong",
  281. "peer", peer, "err", err)
  282. return
  283. }
  284. }
  285. go sw.reconnectToPeer(addr)
  286. }
  287. }
  288. // StopPeerGracefully disconnects from a peer gracefully.
  289. // TODO: handle graceful disconnects.
  290. func (sw *Switch) StopPeerGracefully(peer Peer) {
  291. sw.Logger.Info("Stopping peer gracefully")
  292. sw.stopAndRemovePeer(peer, nil)
  293. }
  294. func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) {
  295. sw.transport.Cleanup(peer)
  296. peer.Stop()
  297. for _, reactor := range sw.reactors {
  298. reactor.RemovePeer(peer, reason)
  299. }
  300. // Removing a peer should go last to avoid a situation where a peer
  301. // reconnect to our node and the switch calls InitPeer before
  302. // RemovePeer is finished.
  303. // https://github.com/tendermint/tendermint/issues/3338
  304. if sw.peers.Remove(peer) {
  305. sw.metrics.Peers.Add(float64(-1))
  306. }
  307. }
  308. // reconnectToPeer tries to reconnect to the addr, first repeatedly
  309. // with a fixed interval, then with exponential backoff.
  310. // If no success after all that, it stops trying, and leaves it
  311. // to the PEX/Addrbook to find the peer with the addr again
  312. // NOTE: this will keep trying even if the handshake or auth fails.
  313. // TODO: be more explicit with error types so we only retry on certain failures
  314. // - ie. if we're getting ErrDuplicatePeer we can stop
  315. // because the addrbook got us the peer back already
  316. func (sw *Switch) reconnectToPeer(addr *NetAddress) {
  317. if sw.reconnecting.Has(string(addr.ID)) {
  318. return
  319. }
  320. sw.reconnecting.Set(string(addr.ID), addr)
  321. defer sw.reconnecting.Delete(string(addr.ID))
  322. start := time.Now()
  323. sw.Logger.Info("Reconnecting to peer", "addr", addr)
  324. for i := 0; i < reconnectAttempts; i++ {
  325. if !sw.IsRunning() {
  326. return
  327. }
  328. err := sw.DialPeerWithAddress(addr)
  329. if err == nil {
  330. return // success
  331. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  332. return
  333. }
  334. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  335. // sleep a set amount
  336. sw.randomSleep(reconnectInterval)
  337. continue
  338. }
  339. sw.Logger.Error("Failed to reconnect to peer. Beginning exponential backoff",
  340. "addr", addr, "elapsed", time.Since(start))
  341. for i := 0; i < reconnectBackOffAttempts; i++ {
  342. if !sw.IsRunning() {
  343. return
  344. }
  345. // sleep an exponentially increasing amount
  346. sleepIntervalSeconds := math.Pow(reconnectBackOffBaseSeconds, float64(i))
  347. sw.randomSleep(time.Duration(sleepIntervalSeconds) * time.Second)
  348. err := sw.DialPeerWithAddress(addr)
  349. if err == nil {
  350. return // success
  351. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  352. return
  353. }
  354. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  355. }
  356. sw.Logger.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start))
  357. }
  358. // SetAddrBook allows to set address book on Switch.
  359. func (sw *Switch) SetAddrBook(addrBook AddrBook) {
  360. sw.addrBook = addrBook
  361. }
  362. // MarkPeerAsGood marks the given peer as good when it did something useful
  363. // like contributed to consensus.
  364. func (sw *Switch) MarkPeerAsGood(peer Peer) {
  365. if sw.addrBook != nil {
  366. sw.addrBook.MarkGood(peer.ID())
  367. }
  368. }
  369. //---------------------------------------------------------------------
  370. // Dialing
  371. type privateAddr interface {
  372. PrivateAddr() bool
  373. }
  374. func isPrivateAddr(err error) bool {
  375. te, ok := errors.Cause(err).(privateAddr)
  376. return ok && te.PrivateAddr()
  377. }
  378. // DialPeersAsync dials a list of peers asynchronously in random order.
  379. // Used to dial peers from config on startup or from unsafe-RPC (trusted sources).
  380. // It ignores ErrNetAddressLookup. However, if there are other errors, first
  381. // encounter is returned.
  382. // Nop if there are no peers.
  383. func (sw *Switch) DialPeersAsync(peers []string) error {
  384. netAddrs, errs := NewNetAddressStrings(peers)
  385. // report all the errors
  386. for _, err := range errs {
  387. sw.Logger.Error("Error in peer's address", "err", err)
  388. }
  389. // return first non-ErrNetAddressLookup error
  390. for _, err := range errs {
  391. if _, ok := err.(ErrNetAddressLookup); ok {
  392. continue
  393. }
  394. return err
  395. }
  396. sw.dialPeersAsync(netAddrs)
  397. return nil
  398. }
  399. func (sw *Switch) dialPeersAsync(netAddrs []*NetAddress) {
  400. ourAddr := sw.NetAddress()
  401. // TODO: this code feels like it's in the wrong place.
  402. // The integration tests depend on the addrBook being saved
  403. // right away but maybe we can change that. Recall that
  404. // the addrBook is only written to disk every 2min
  405. if sw.addrBook != nil {
  406. // add peers to `addrBook`
  407. for _, netAddr := range netAddrs {
  408. // do not add our address or ID
  409. if !netAddr.Same(ourAddr) {
  410. if err := sw.addrBook.AddAddress(netAddr, ourAddr); err != nil {
  411. if isPrivateAddr(err) {
  412. sw.Logger.Debug("Won't add peer's address to addrbook", "err", err)
  413. } else {
  414. sw.Logger.Error("Can't add peer's address to addrbook", "err", err)
  415. }
  416. }
  417. }
  418. }
  419. // Persist some peers to disk right away.
  420. // NOTE: integration tests depend on this
  421. sw.addrBook.Save()
  422. }
  423. // permute the list, dial them in random order.
  424. perm := sw.rng.Perm(len(netAddrs))
  425. for i := 0; i < len(perm); i++ {
  426. go func(i int) {
  427. j := perm[i]
  428. addr := netAddrs[j]
  429. if addr.Same(ourAddr) {
  430. sw.Logger.Debug("Ignore attempt to connect to ourselves", "addr", addr, "ourAddr", ourAddr)
  431. return
  432. }
  433. sw.randomSleep(0)
  434. err := sw.DialPeerWithAddress(addr)
  435. if err != nil {
  436. switch err.(type) {
  437. case ErrSwitchConnectToSelf, ErrSwitchDuplicatePeerID, ErrCurrentlyDialingOrExistingAddress:
  438. sw.Logger.Debug("Error dialing peer", "err", err)
  439. default:
  440. sw.Logger.Error("Error dialing peer", "err", err)
  441. }
  442. }
  443. }(i)
  444. }
  445. }
  446. // DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects
  447. // and authenticates successfully.
  448. // If we're currently dialing this address or it belongs to an existing peer,
  449. // ErrCurrentlyDialingOrExistingAddress is returned.
  450. func (sw *Switch) DialPeerWithAddress(addr *NetAddress) error {
  451. if sw.IsDialingOrExistingAddress(addr) {
  452. return ErrCurrentlyDialingOrExistingAddress{addr.String()}
  453. }
  454. sw.dialing.Set(string(addr.ID), addr)
  455. defer sw.dialing.Delete(string(addr.ID))
  456. return sw.addOutboundPeerWithConfig(addr, sw.config)
  457. }
  458. // sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds]
  459. func (sw *Switch) randomSleep(interval time.Duration) {
  460. r := time.Duration(sw.rng.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond
  461. time.Sleep(r + interval)
  462. }
  463. // IsDialingOrExistingAddress returns true if switch has a peer with the given
  464. // address or dialing it at the moment.
  465. func (sw *Switch) IsDialingOrExistingAddress(addr *NetAddress) bool {
  466. return sw.dialing.Has(string(addr.ID)) ||
  467. sw.peers.Has(addr.ID) ||
  468. (!sw.config.AllowDuplicateIP && sw.peers.HasIP(addr.IP))
  469. }
  470. // AddPersistentPeers allows you to set persistent peers. It ignores
  471. // ErrNetAddressLookup. However, if there are other errors, first encounter is
  472. // returned.
  473. func (sw *Switch) AddPersistentPeers(addrs []string) error {
  474. sw.Logger.Info("Adding persistent peers", "addrs", addrs)
  475. netAddrs, errs := NewNetAddressStrings(addrs)
  476. // report all the errors
  477. for _, err := range errs {
  478. sw.Logger.Error("Error in peer's address", "err", err)
  479. }
  480. // return first non-ErrNetAddressLookup error
  481. for _, err := range errs {
  482. if _, ok := err.(ErrNetAddressLookup); ok {
  483. continue
  484. }
  485. return err
  486. }
  487. sw.persistentPeersAddrs = netAddrs
  488. return nil
  489. }
  490. func (sw *Switch) AddUnconditionalPeerIDs(ids []string) error {
  491. sw.Logger.Info("Adding unconditional peer ids", "ids", ids)
  492. for i, id := range ids {
  493. err := validateID(ID(id))
  494. if err != nil {
  495. return errors.Wrapf(err, "wrong ID #%d", i)
  496. }
  497. sw.unconditionalPeerIDs[ID(id)] = struct{}{}
  498. }
  499. return nil
  500. }
  501. func (sw *Switch) isPeerPersistentFn() func(*NetAddress) bool {
  502. return func(na *NetAddress) bool {
  503. return sw.IsPeerPersistent(na)
  504. }
  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.isPeerPersistentFn(),
  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.isPeerPersistentFn(),
  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.isPeerPersistentFn()(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. }