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.

1064 lines
29 KiB

p2p: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
4 years ago
p2p: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
4 years ago
p2p: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
4 years ago
p2p: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
4 years ago
p2p: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
4 years ago
p2p: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
4 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: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
4 years ago
p2p: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
4 years ago
p2p: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
4 years ago
p2p: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
4 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: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
4 years ago
p2p: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
4 years ago
p2p: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
4 years ago
p2p: implement new Transport interface (#5791) This implements a new `Transport` interface and related types for the P2P refactor in #5670. Previously, `conn.MConnection` was very tightly coupled to the `Peer` implementation -- in order to allow alternative non-multiplexed transports (e.g. QUIC), MConnection has now been moved below the `Transport` interface, as `MConnTransport`, and decoupled from the peer. Since the `p2p` package is not covered by our Go API stability, this is not considered a breaking change, and not listed in the changelog. The initial approach was to implement the new interface in its final form (which also involved possible protocol changes, see https://github.com/tendermint/spec/pull/227). However, it turned out that this would require a large amount of changes to existing P2P code because of the previous tight coupling between `Peer` and `MConnection` and the reliance on subtleties in the MConnection behavior. Instead, I have broadened the `Transport` interface to expose much of the existing MConnection interface, preserved much of the existing MConnection logic and behavior in the transport implementation, and tried to make as few changes to the rest of the P2P stack as possible. We will instead reduce this interface gradually as we refactor other parts of the P2P stack. The low-level transport code and protocol (e.g. MConnection, SecretConnection and so on) has not been significantly changed, and refactoring this is not a priority until we come up with a plan for QUIC adoption, as we may end up discarding the MConnection code entirely. There are no tests of the new `MConnTransport`, as this code is likely to evolve as we proceed with the P2P refactor, but tests should be added before a final release. The E2E tests are sufficient for basic validation in the meanwhile.
4 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. "context"
  4. "fmt"
  5. "io"
  6. "math"
  7. mrand "math/rand"
  8. "net"
  9. "sync"
  10. "time"
  11. "github.com/tendermint/tendermint/config"
  12. "github.com/tendermint/tendermint/crypto"
  13. "github.com/tendermint/tendermint/internal/p2p/conn"
  14. "github.com/tendermint/tendermint/libs/cmap"
  15. tmrand "github.com/tendermint/tendermint/libs/rand"
  16. "github.com/tendermint/tendermint/libs/service"
  17. "github.com/tendermint/tendermint/types"
  18. )
  19. const (
  20. // wait a random amount of time from this interval
  21. // before dialing peers or reconnecting to help prevent DoS
  22. dialRandomizerIntervalMilliseconds = 3000
  23. // repeatedly try to reconnect for a few minutes
  24. // ie. 5 * 20 = 100s
  25. reconnectAttempts = 20
  26. reconnectInterval = 5 * time.Second
  27. // then move into exponential backoff mode for ~1day
  28. // ie. 3**10 = 16hrs
  29. reconnectBackOffAttempts = 10
  30. reconnectBackOffBaseSeconds = 3
  31. defaultFilterTimeout = 5 * time.Second
  32. )
  33. // MConnConfig returns an MConnConfig with fields updated
  34. // from the P2PConfig.
  35. func MConnConfig(cfg *config.P2PConfig) conn.MConnConfig {
  36. mConfig := conn.DefaultMConnConfig()
  37. mConfig.FlushThrottle = cfg.FlushThrottleTimeout
  38. mConfig.SendRate = cfg.SendRate
  39. mConfig.RecvRate = cfg.RecvRate
  40. mConfig.MaxPacketMsgPayloadSize = cfg.MaxPacketMsgPayloadSize
  41. return mConfig
  42. }
  43. //-----------------------------------------------------------------------------
  44. // An AddrBook represents an address book from the pex package, which is used
  45. // to store peer addresses.
  46. type AddrBook interface {
  47. AddAddress(addr *NetAddress, src *NetAddress) error
  48. AddPrivateIDs([]string)
  49. AddOurAddress(*NetAddress)
  50. OurAddress(*NetAddress) bool
  51. MarkGood(types.NodeID)
  52. RemoveAddress(*NetAddress)
  53. HasAddress(*NetAddress) bool
  54. Save()
  55. }
  56. // ConnFilterFunc is a callback for connection filtering. If it returns an
  57. // error, the connection is rejected. The set of existing connections is passed
  58. // along with the new connection and all resolved IPs.
  59. type ConnFilterFunc func(ConnSet, net.Conn, []net.IP) error
  60. // PeerFilterFunc to be implemented by filter hooks after a new Peer has been
  61. // fully setup.
  62. type PeerFilterFunc func(IPeerSet, Peer) error
  63. // ConnDuplicateIPFilter resolves and keeps all ips for an incoming connection
  64. // and refuses new ones if they come from a known ip.
  65. var ConnDuplicateIPFilter ConnFilterFunc = func(cs ConnSet, c net.Conn, ips []net.IP) error {
  66. for _, ip := range ips {
  67. if cs.HasIP(ip) {
  68. return ErrRejected{
  69. conn: c,
  70. err: fmt.Errorf("ip<%v> already connected", ip),
  71. isDuplicate: true,
  72. }
  73. }
  74. }
  75. return nil
  76. }
  77. //-----------------------------------------------------------------------------
  78. // Switch handles peer connections and exposes an API to receive incoming messages
  79. // on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one
  80. // or more `Channels`. So while sending outgoing messages is typically performed on the peer,
  81. // incoming messages are received on the reactor.
  82. type Switch struct {
  83. service.BaseService
  84. config *config.P2PConfig
  85. reactors map[string]Reactor
  86. chDescs []*conn.ChannelDescriptor
  87. reactorsByCh map[byte]Reactor
  88. peers *PeerSet
  89. dialing *cmap.CMap
  90. reconnecting *cmap.CMap
  91. nodeInfo types.NodeInfo // our node info
  92. nodeKey types.NodeKey // our node privkey
  93. addrBook AddrBook
  94. // peers addresses with whom we'll maintain constant connection
  95. persistentPeersAddrs []*NetAddress
  96. unconditionalPeerIDs map[types.NodeID]struct{}
  97. transport Transport
  98. filterTimeout time.Duration
  99. peerFilters []PeerFilterFunc
  100. connFilters []ConnFilterFunc
  101. conns ConnSet
  102. metrics *Metrics
  103. }
  104. // NetAddress returns the first address the switch is listening on,
  105. // or nil if no addresses are found.
  106. func (sw *Switch) NetAddress() *NetAddress {
  107. endpoints := sw.transport.Endpoints()
  108. if len(endpoints) == 0 {
  109. return nil
  110. }
  111. return &NetAddress{
  112. ID: sw.nodeInfo.NodeID,
  113. IP: endpoints[0].IP,
  114. Port: endpoints[0].Port,
  115. }
  116. }
  117. // SwitchOption sets an optional parameter on the Switch.
  118. type SwitchOption func(*Switch)
  119. // NewSwitch creates a new Switch with the given config.
  120. func NewSwitch(
  121. cfg *config.P2PConfig,
  122. transport Transport,
  123. options ...SwitchOption,
  124. ) *Switch {
  125. sw := &Switch{
  126. config: cfg,
  127. reactors: make(map[string]Reactor),
  128. chDescs: make([]*conn.ChannelDescriptor, 0),
  129. reactorsByCh: make(map[byte]Reactor),
  130. peers: NewPeerSet(),
  131. dialing: cmap.NewCMap(),
  132. reconnecting: cmap.NewCMap(),
  133. metrics: NopMetrics(),
  134. transport: transport,
  135. persistentPeersAddrs: make([]*NetAddress, 0),
  136. unconditionalPeerIDs: make(map[types.NodeID]struct{}),
  137. filterTimeout: defaultFilterTimeout,
  138. conns: NewConnSet(),
  139. }
  140. // Ensure PRNG is reseeded.
  141. tmrand.Reseed()
  142. sw.BaseService = *service.NewBaseService(nil, "P2P Switch", sw)
  143. for _, option := range options {
  144. option(sw)
  145. }
  146. return sw
  147. }
  148. // SwitchFilterTimeout sets the timeout used for peer filters.
  149. func SwitchFilterTimeout(timeout time.Duration) SwitchOption {
  150. return func(sw *Switch) { sw.filterTimeout = timeout }
  151. }
  152. // SwitchPeerFilters sets the filters for rejection of new peers.
  153. func SwitchPeerFilters(filters ...PeerFilterFunc) SwitchOption {
  154. return func(sw *Switch) { sw.peerFilters = filters }
  155. }
  156. // SwitchConnFilters sets the filters for rejection of connections.
  157. func SwitchConnFilters(filters ...ConnFilterFunc) SwitchOption {
  158. return func(sw *Switch) { sw.connFilters = filters }
  159. }
  160. // WithMetrics sets the metrics.
  161. func WithMetrics(metrics *Metrics) SwitchOption {
  162. return func(sw *Switch) { sw.metrics = metrics }
  163. }
  164. //---------------------------------------------------------------------
  165. // Switch setup
  166. // AddReactor adds the given reactor to the switch.
  167. // NOTE: Not goroutine safe.
  168. func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor {
  169. for _, chDesc := range reactor.GetChannels() {
  170. chID := chDesc.ID
  171. // No two reactors can share the same channel.
  172. if sw.reactorsByCh[chID] != nil {
  173. panic(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor))
  174. }
  175. sw.chDescs = append(sw.chDescs, chDesc)
  176. sw.reactorsByCh[chID] = reactor
  177. }
  178. sw.reactors[name] = reactor
  179. reactor.SetSwitch(sw)
  180. return reactor
  181. }
  182. // RemoveReactor removes the given Reactor from the Switch.
  183. // NOTE: Not goroutine safe.
  184. func (sw *Switch) RemoveReactor(name string, reactor Reactor) {
  185. for _, chDesc := range reactor.GetChannels() {
  186. // remove channel description
  187. for i := 0; i < len(sw.chDescs); i++ {
  188. if chDesc.ID == sw.chDescs[i].ID {
  189. sw.chDescs = append(sw.chDescs[:i], sw.chDescs[i+1:]...)
  190. break
  191. }
  192. }
  193. delete(sw.reactorsByCh, chDesc.ID)
  194. }
  195. delete(sw.reactors, name)
  196. reactor.SetSwitch(nil)
  197. }
  198. // Reactors returns a map of reactors registered on the switch.
  199. // NOTE: Not goroutine safe.
  200. func (sw *Switch) Reactors() map[string]Reactor {
  201. return sw.reactors
  202. }
  203. // Reactor returns the reactor with the given name.
  204. // NOTE: Not goroutine safe.
  205. func (sw *Switch) Reactor(name string) Reactor {
  206. return sw.reactors[name]
  207. }
  208. // SetNodeInfo sets the switch's NodeInfo for checking compatibility and handshaking with other nodes.
  209. // NOTE: Not goroutine safe.
  210. func (sw *Switch) SetNodeInfo(nodeInfo types.NodeInfo) {
  211. sw.nodeInfo = nodeInfo
  212. }
  213. // NodeInfo returns the switch's NodeInfo.
  214. // NOTE: Not goroutine safe.
  215. func (sw *Switch) NodeInfo() types.NodeInfo {
  216. return sw.nodeInfo
  217. }
  218. // SetNodeKey sets the switch's private key for authenticated encryption.
  219. // NOTE: Not goroutine safe.
  220. func (sw *Switch) SetNodeKey(nodeKey types.NodeKey) {
  221. sw.nodeKey = nodeKey
  222. }
  223. //---------------------------------------------------------------------
  224. // Service start/stop
  225. // OnStart implements BaseService. It starts all the reactors and peers.
  226. func (sw *Switch) OnStart() error {
  227. // FIXME: Temporary hack to pass channel descriptors to MConn transport,
  228. // since they are not available when it is constructed. This will be
  229. // fixed when we implement the new router abstraction.
  230. if t, ok := sw.transport.(*MConnTransport); ok {
  231. t.channelDescs = sw.chDescs
  232. }
  233. // Start reactors
  234. for _, reactor := range sw.reactors {
  235. err := reactor.Start()
  236. if err != nil {
  237. return fmt.Errorf("failed to start %v: %w", reactor, err)
  238. }
  239. }
  240. // Start accepting Peers.
  241. go sw.acceptRoutine()
  242. return nil
  243. }
  244. // OnStop implements BaseService. It stops all peers and reactors.
  245. func (sw *Switch) OnStop() {
  246. // Stop peers
  247. for _, p := range sw.peers.List() {
  248. sw.stopAndRemovePeer(p, nil)
  249. }
  250. // Stop reactors
  251. sw.Logger.Debug("Switch: Stopping reactors")
  252. for _, reactor := range sw.reactors {
  253. if err := reactor.Stop(); err != nil {
  254. sw.Logger.Error("error while stopping reactor", "reactor", reactor, "error", err)
  255. }
  256. }
  257. }
  258. //---------------------------------------------------------------------
  259. // Peers
  260. // Broadcast runs a go routine for each attempted send, which will block trying
  261. // to send for defaultSendTimeoutSeconds. Returns a channel which receives
  262. // success values for each attempted send (false if times out). Channel will be
  263. // closed once msg bytes are sent to all peers (or time out).
  264. //
  265. // NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved.
  266. func (sw *Switch) Broadcast(chID byte, msgBytes []byte) chan bool {
  267. sw.Logger.Debug("Broadcast", "channel", chID, "msgBytes", msgBytes)
  268. peers := sw.peers.List()
  269. var wg sync.WaitGroup
  270. wg.Add(len(peers))
  271. successChan := make(chan bool, len(peers))
  272. for _, peer := range peers {
  273. go func(p Peer) {
  274. defer wg.Done()
  275. success := p.Send(chID, msgBytes)
  276. successChan <- success
  277. }(peer)
  278. }
  279. go func() {
  280. wg.Wait()
  281. close(successChan)
  282. }()
  283. return successChan
  284. }
  285. // NumPeers returns the count of outbound/inbound and outbound-dialing peers.
  286. // unconditional peers are not counted here.
  287. func (sw *Switch) NumPeers() (outbound, inbound, dialing int) {
  288. peers := sw.peers.List()
  289. for _, peer := range peers {
  290. if peer.IsOutbound() {
  291. if !sw.IsPeerUnconditional(peer.ID()) {
  292. outbound++
  293. }
  294. } else {
  295. if !sw.IsPeerUnconditional(peer.ID()) {
  296. inbound++
  297. }
  298. }
  299. }
  300. dialing = sw.dialing.Size()
  301. return
  302. }
  303. func (sw *Switch) IsPeerUnconditional(id types.NodeID) bool {
  304. _, ok := sw.unconditionalPeerIDs[id]
  305. return ok
  306. }
  307. // MaxNumOutboundPeers returns a maximum number of outbound peers.
  308. func (sw *Switch) MaxNumOutboundPeers() int {
  309. return sw.config.MaxNumOutboundPeers
  310. }
  311. // Peers returns the set of peers that are connected to the switch.
  312. func (sw *Switch) Peers() IPeerSet {
  313. return sw.peers
  314. }
  315. // StopPeerForError disconnects from a peer due to external error.
  316. // If the peer is persistent, it will attempt to reconnect.
  317. // TODO: make record depending on reason.
  318. func (sw *Switch) StopPeerForError(peer Peer, reason interface{}) {
  319. if !peer.IsRunning() {
  320. return
  321. }
  322. sw.Logger.Error("Stopping peer for error", "peer", peer, "err", reason)
  323. sw.stopAndRemovePeer(peer, reason)
  324. if peer.IsPersistent() {
  325. var addr *NetAddress
  326. if peer.IsOutbound() { // socket address for outbound peers
  327. addr = peer.SocketAddr()
  328. } else { // self-reported address for inbound peers
  329. var err error
  330. addr, err = peer.NodeInfo().NetAddress()
  331. if err != nil {
  332. sw.Logger.Error("Wanted to reconnect to inbound peer, but self-reported address is wrong",
  333. "peer", peer, "err", err)
  334. return
  335. }
  336. }
  337. go sw.reconnectToPeer(addr)
  338. }
  339. }
  340. // StopPeerGracefully disconnects from a peer gracefully.
  341. // TODO: handle graceful disconnects.
  342. func (sw *Switch) StopPeerGracefully(peer Peer) {
  343. sw.Logger.Info("Stopping peer gracefully")
  344. sw.stopAndRemovePeer(peer, nil)
  345. }
  346. func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) {
  347. if err := peer.Stop(); err != nil {
  348. sw.Logger.Error("error while stopping peer", "error", err) // TODO: should return error to be handled accordingly
  349. }
  350. for _, reactor := range sw.reactors {
  351. reactor.RemovePeer(peer, reason)
  352. }
  353. // Removing a peer should go last to avoid a situation where a peer
  354. // reconnect to our node and the switch calls InitPeer before
  355. // RemovePeer is finished.
  356. // https://github.com/tendermint/tendermint/issues/3338
  357. if sw.peers.Remove(peer) {
  358. sw.metrics.Peers.Add(float64(-1))
  359. }
  360. sw.conns.RemoveAddr(peer.RemoteAddr())
  361. }
  362. // reconnectToPeer tries to reconnect to the addr, first repeatedly
  363. // with a fixed interval, then with exponential backoff.
  364. // If no success after all that, it stops trying, and leaves it
  365. // to the PEX/Addrbook to find the peer with the addr again
  366. // NOTE: this will keep trying even if the handshake or auth fails.
  367. // TODO: be more explicit with error types so we only retry on certain failures
  368. // - ie. if we're getting ErrDuplicatePeer we can stop
  369. // because the addrbook got us the peer back already
  370. func (sw *Switch) reconnectToPeer(addr *NetAddress) {
  371. if _, exists := sw.reconnecting.GetOrSet(string(addr.ID), addr); exists {
  372. return
  373. }
  374. defer sw.reconnecting.Delete(string(addr.ID))
  375. start := time.Now()
  376. sw.Logger.Info("Reconnecting to peer", "addr", addr)
  377. for i := 0; i < reconnectAttempts; i++ {
  378. if !sw.IsRunning() {
  379. return
  380. }
  381. err := sw.DialPeerWithAddress(addr)
  382. if err == nil {
  383. return // success
  384. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  385. return
  386. }
  387. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  388. // sleep a set amount
  389. sw.randomSleep(reconnectInterval)
  390. continue
  391. }
  392. sw.Logger.Error("Failed to reconnect to peer. Beginning exponential backoff",
  393. "addr", addr, "elapsed", time.Since(start))
  394. for i := 0; i < reconnectBackOffAttempts; i++ {
  395. if !sw.IsRunning() {
  396. return
  397. }
  398. // sleep an exponentially increasing amount
  399. sleepIntervalSeconds := math.Pow(reconnectBackOffBaseSeconds, float64(i))
  400. sw.randomSleep(time.Duration(sleepIntervalSeconds) * time.Second)
  401. err := sw.DialPeerWithAddress(addr)
  402. if err == nil {
  403. return // success
  404. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  405. return
  406. }
  407. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  408. }
  409. sw.Logger.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start))
  410. }
  411. // SetAddrBook allows to set address book on Switch.
  412. func (sw *Switch) SetAddrBook(addrBook AddrBook) {
  413. sw.addrBook = addrBook
  414. }
  415. // MarkPeerAsGood marks the given peer as good when it did something useful
  416. // like contributed to consensus.
  417. func (sw *Switch) MarkPeerAsGood(peer Peer) {
  418. if sw.addrBook != nil {
  419. sw.addrBook.MarkGood(peer.ID())
  420. }
  421. }
  422. //---------------------------------------------------------------------
  423. // Dialing
  424. type privateAddr interface {
  425. PrivateAddr() bool
  426. }
  427. func isPrivateAddr(err error) bool {
  428. te, ok := err.(privateAddr)
  429. return ok && te.PrivateAddr()
  430. }
  431. // DialPeersAsync dials a list of peers asynchronously in random order.
  432. // Used to dial peers from config on startup or from unsafe-RPC (trusted sources).
  433. // It ignores ErrNetAddressLookup. However, if there are other errors, first
  434. // encounter is returned.
  435. // Nop if there are no peers.
  436. func (sw *Switch) DialPeersAsync(peers []string) error {
  437. netAddrs, errs := NewNetAddressStrings(peers)
  438. // report all the errors
  439. for _, err := range errs {
  440. sw.Logger.Error("Error in peer's address", "err", err)
  441. }
  442. // return first non-ErrNetAddressLookup error
  443. for _, err := range errs {
  444. if _, ok := err.(types.ErrNetAddressLookup); ok {
  445. continue
  446. }
  447. return err
  448. }
  449. sw.dialPeersAsync(netAddrs)
  450. return nil
  451. }
  452. func (sw *Switch) dialPeersAsync(netAddrs []*NetAddress) {
  453. ourAddr := sw.NetAddress()
  454. // TODO: this code feels like it's in the wrong place.
  455. // The integration tests depend on the addrBook being saved
  456. // right away but maybe we can change that. Recall that
  457. // the addrBook is only written to disk every 2min
  458. if sw.addrBook != nil {
  459. // add peers to `addrBook`
  460. for _, netAddr := range netAddrs {
  461. // do not add our address or ID
  462. if !netAddr.Same(ourAddr) {
  463. if err := sw.addrBook.AddAddress(netAddr, ourAddr); err != nil {
  464. if isPrivateAddr(err) {
  465. sw.Logger.Debug("Won't add peer's address to addrbook", "err", err)
  466. } else {
  467. sw.Logger.Error("Can't add peer's address to addrbook", "err", err)
  468. }
  469. }
  470. }
  471. }
  472. // Persist some peers to disk right away.
  473. // NOTE: integration tests depend on this
  474. sw.addrBook.Save()
  475. }
  476. // permute the list, dial them in random order.
  477. perm := mrand.Perm(len(netAddrs))
  478. for i := 0; i < len(perm); i++ {
  479. go func(i int) {
  480. j := perm[i]
  481. addr := netAddrs[j]
  482. if addr.Same(ourAddr) {
  483. sw.Logger.Debug("Ignore attempt to connect to ourselves", "addr", addr, "ourAddr", ourAddr)
  484. return
  485. }
  486. sw.randomSleep(0)
  487. err := sw.DialPeerWithAddress(addr)
  488. if err != nil {
  489. switch err.(type) {
  490. case ErrSwitchConnectToSelf, ErrSwitchDuplicatePeerID, ErrCurrentlyDialingOrExistingAddress:
  491. sw.Logger.Debug("Error dialing peer", "err", err)
  492. default:
  493. sw.Logger.Error("Error dialing peer", "err", err)
  494. }
  495. }
  496. }(i)
  497. }
  498. }
  499. // DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects
  500. // and authenticates successfully.
  501. // If we're currently dialing this address or it belongs to an existing peer,
  502. // ErrCurrentlyDialingOrExistingAddress is returned.
  503. func (sw *Switch) DialPeerWithAddress(addr *NetAddress) error {
  504. if sw.IsDialingOrExistingAddress(addr) {
  505. return ErrCurrentlyDialingOrExistingAddress{addr.String()}
  506. }
  507. sw.dialing.Set(string(addr.ID), addr)
  508. defer sw.dialing.Delete(string(addr.ID))
  509. return sw.addOutboundPeerWithConfig(addr, sw.config)
  510. }
  511. // sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds]
  512. func (sw *Switch) randomSleep(interval time.Duration) {
  513. // nolint:gosec // G404: Use of weak random number generator
  514. r := time.Duration(mrand.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond
  515. time.Sleep(r + interval)
  516. }
  517. // IsDialingOrExistingAddress returns true if switch has a peer with the given
  518. // address or dialing it at the moment.
  519. func (sw *Switch) IsDialingOrExistingAddress(addr *NetAddress) bool {
  520. return sw.dialing.Has(string(addr.ID)) ||
  521. sw.peers.Has(addr.ID) ||
  522. (!sw.config.AllowDuplicateIP && sw.peers.HasIP(addr.IP))
  523. }
  524. // AddPersistentPeers allows you to set persistent peers. It ignores
  525. // ErrNetAddressLookup. However, if there are other errors, first encounter is
  526. // returned.
  527. func (sw *Switch) AddPersistentPeers(addrs []string) error {
  528. sw.Logger.Info("Adding persistent peers", "addrs", addrs)
  529. netAddrs, errs := NewNetAddressStrings(addrs)
  530. // report all the errors
  531. for _, err := range errs {
  532. sw.Logger.Error("Error in peer's address", "err", err)
  533. }
  534. // return first non-ErrNetAddressLookup error
  535. for _, err := range errs {
  536. if _, ok := err.(types.ErrNetAddressLookup); ok {
  537. continue
  538. }
  539. return err
  540. }
  541. sw.persistentPeersAddrs = netAddrs
  542. return nil
  543. }
  544. func (sw *Switch) AddUnconditionalPeerIDs(ids []string) error {
  545. sw.Logger.Info("Adding unconditional peer ids", "ids", ids)
  546. for i, id := range ids {
  547. err := types.NodeID(id).Validate()
  548. if err != nil {
  549. return fmt.Errorf("wrong ID #%d: %w", i, err)
  550. }
  551. sw.unconditionalPeerIDs[types.NodeID(id)] = struct{}{}
  552. }
  553. return nil
  554. }
  555. func (sw *Switch) AddPrivatePeerIDs(ids []string) error {
  556. validIDs := make([]string, 0, len(ids))
  557. for i, id := range ids {
  558. err := types.NodeID(id).Validate()
  559. if err != nil {
  560. return fmt.Errorf("wrong ID #%d: %w", i, err)
  561. }
  562. validIDs = append(validIDs, id)
  563. }
  564. sw.addrBook.AddPrivateIDs(validIDs)
  565. return nil
  566. }
  567. func (sw *Switch) IsPeerPersistent(na *NetAddress) bool {
  568. for _, pa := range sw.persistentPeersAddrs {
  569. if pa.Equals(na) {
  570. return true
  571. }
  572. }
  573. return false
  574. }
  575. func (sw *Switch) acceptRoutine() {
  576. for {
  577. var peerNodeInfo types.NodeInfo
  578. c, err := sw.transport.Accept()
  579. if err == nil {
  580. // NOTE: The legacy MConn transport did handshaking in Accept(),
  581. // which was asynchronous and avoided head-of-line-blocking.
  582. // However, as handshakes are being migrated out from the transport,
  583. // we just do it synchronously here for now.
  584. peerNodeInfo, _, err = sw.handshakePeer(c, "")
  585. }
  586. if err == nil {
  587. err = sw.filterConn(c.(*mConnConnection).conn)
  588. }
  589. if err != nil {
  590. if c != nil {
  591. _ = c.Close()
  592. }
  593. if err == io.EOF {
  594. err = ErrTransportClosed{}
  595. }
  596. switch err := err.(type) {
  597. case ErrRejected:
  598. addr := err.Addr()
  599. if err.IsSelf() {
  600. // Remove the given address from the address book and add to our addresses
  601. // to avoid dialing in the future.
  602. sw.addrBook.RemoveAddress(&addr)
  603. sw.addrBook.AddOurAddress(&addr)
  604. }
  605. if err.IsIncompatible() {
  606. sw.addrBook.RemoveAddress(&addr)
  607. }
  608. sw.Logger.Info(
  609. "Inbound Peer rejected",
  610. "err", err,
  611. "numPeers", sw.peers.Size(),
  612. )
  613. continue
  614. case ErrFilterTimeout:
  615. sw.Logger.Error(
  616. "Peer filter timed out",
  617. "err", err,
  618. )
  619. continue
  620. case ErrTransportClosed:
  621. sw.Logger.Error(
  622. "Stopped accept routine, as transport is closed",
  623. "numPeers", sw.peers.Size(),
  624. )
  625. default:
  626. sw.Logger.Error(
  627. "Accept on transport errored",
  628. "err", err,
  629. "numPeers", sw.peers.Size(),
  630. )
  631. // We could instead have a retry loop around the acceptRoutine,
  632. // but that would need to stop and let the node shutdown eventually.
  633. // So might as well panic and let process managers restart the node.
  634. // There's no point in letting the node run without the acceptRoutine,
  635. // since it won't be able to accept new connections.
  636. panic(fmt.Errorf("accept routine exited: %v", err))
  637. }
  638. break
  639. }
  640. isPersistent := false
  641. addr, err := peerNodeInfo.NetAddress()
  642. if err == nil {
  643. isPersistent = sw.IsPeerPersistent(addr)
  644. }
  645. p := newPeer(
  646. peerNodeInfo,
  647. newPeerConn(false, isPersistent, c),
  648. sw.reactorsByCh,
  649. sw.StopPeerForError,
  650. PeerMetrics(sw.metrics),
  651. )
  652. if !sw.IsPeerUnconditional(p.NodeInfo().ID()) {
  653. // Ignore connection if we already have enough peers.
  654. _, in, _ := sw.NumPeers()
  655. if in >= sw.config.MaxNumInboundPeers {
  656. sw.Logger.Info(
  657. "Ignoring inbound connection: already have enough inbound peers",
  658. "address", p.SocketAddr(),
  659. "have", in,
  660. "max", sw.config.MaxNumInboundPeers,
  661. )
  662. _ = p.CloseConn()
  663. continue
  664. }
  665. }
  666. if err := sw.addPeer(p); err != nil {
  667. _ = p.CloseConn()
  668. if p.IsRunning() {
  669. _ = p.Stop()
  670. }
  671. sw.conns.RemoveAddr(p.RemoteAddr())
  672. sw.Logger.Info(
  673. "Ignoring inbound connection: error while adding peer",
  674. "err", err,
  675. "id", p.ID(),
  676. )
  677. }
  678. }
  679. }
  680. // dial the peer; make secret connection; authenticate against the dialed ID;
  681. // add the peer.
  682. // if dialing fails, start the reconnect loop. If handshake fails, it's over.
  683. // If peer is started successfully, reconnectLoop will start when
  684. // StopPeerForError is called.
  685. func (sw *Switch) addOutboundPeerWithConfig(
  686. addr *NetAddress,
  687. cfg *config.P2PConfig,
  688. ) error {
  689. sw.Logger.Info("Dialing peer", "address", addr)
  690. // XXX(xla): Remove the leakage of test concerns in implementation.
  691. if cfg.TestDialFail {
  692. go sw.reconnectToPeer(addr)
  693. return fmt.Errorf("dial err (peerConfig.DialFail == true)")
  694. }
  695. // Hardcoded timeout moved from MConn transport during refactoring.
  696. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  697. defer cancel()
  698. var peerNodeInfo types.NodeInfo
  699. c, err := sw.transport.Dial(ctx, Endpoint{
  700. Protocol: MConnProtocol,
  701. IP: addr.IP,
  702. Port: addr.Port,
  703. })
  704. if err == nil {
  705. peerNodeInfo, _, err = sw.handshakePeer(c, addr.ID)
  706. }
  707. if err == nil {
  708. err = sw.filterConn(c.(*mConnConnection).conn)
  709. }
  710. if err != nil {
  711. if c != nil {
  712. _ = c.Close()
  713. }
  714. if e, ok := err.(ErrRejected); ok {
  715. if e.IsSelf() {
  716. // Remove the given address from the address book and add to our addresses
  717. // to avoid dialing in the future.
  718. sw.addrBook.RemoveAddress(addr)
  719. sw.addrBook.AddOurAddress(addr)
  720. }
  721. if e.IsIncompatible() {
  722. sw.addrBook.RemoveAddress(addr)
  723. }
  724. return err
  725. }
  726. // retry persistent peers after
  727. // any dial error besides IsSelf()
  728. if sw.IsPeerPersistent(addr) {
  729. go sw.reconnectToPeer(addr)
  730. }
  731. return err
  732. }
  733. p := newPeer(
  734. peerNodeInfo,
  735. newPeerConn(true, sw.IsPeerPersistent(addr), c),
  736. sw.reactorsByCh,
  737. sw.StopPeerForError,
  738. PeerMetrics(sw.metrics),
  739. )
  740. if err := sw.addPeer(p); err != nil {
  741. _ = p.CloseConn()
  742. if p.IsRunning() {
  743. _ = p.Stop()
  744. }
  745. sw.conns.RemoveAddr(p.RemoteAddr())
  746. return err
  747. }
  748. return nil
  749. }
  750. func (sw *Switch) handshakePeer(
  751. c Connection,
  752. expectPeerID types.NodeID,
  753. ) (types.NodeInfo, crypto.PubKey, error) {
  754. // Moved from transport and hardcoded until legacy P2P stack removal.
  755. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  756. defer cancel()
  757. peerInfo, peerKey, err := c.Handshake(ctx, sw.nodeInfo, sw.nodeKey.PrivKey)
  758. if err != nil {
  759. return peerInfo, peerKey, ErrRejected{
  760. conn: c.(*mConnConnection).conn,
  761. err: fmt.Errorf("handshake failed: %v", err),
  762. isAuthFailure: true,
  763. }
  764. }
  765. if err = peerInfo.Validate(); err != nil {
  766. return peerInfo, peerKey, ErrRejected{
  767. conn: c.(*mConnConnection).conn,
  768. err: err,
  769. isNodeInfoInvalid: true,
  770. }
  771. }
  772. // For outgoing conns, ensure connection key matches dialed key.
  773. if expectPeerID != "" {
  774. peerID := types.NodeIDFromPubKey(peerKey)
  775. if expectPeerID != peerID {
  776. return peerInfo, peerKey, ErrRejected{
  777. conn: c.(*mConnConnection).conn,
  778. id: peerID,
  779. err: fmt.Errorf(
  780. "conn.ID (%v) dialed ID (%v) mismatch",
  781. peerID,
  782. expectPeerID,
  783. ),
  784. isAuthFailure: true,
  785. }
  786. }
  787. }
  788. if sw.nodeInfo.ID() == peerInfo.ID() {
  789. return peerInfo, peerKey, ErrRejected{
  790. addr: *types.NewNetAddress(peerInfo.ID(), c.(*mConnConnection).conn.RemoteAddr()),
  791. conn: c.(*mConnConnection).conn,
  792. id: peerInfo.ID(),
  793. isSelf: true,
  794. }
  795. }
  796. if err = sw.nodeInfo.CompatibleWith(peerInfo); err != nil {
  797. return peerInfo, peerKey, ErrRejected{
  798. conn: c.(*mConnConnection).conn,
  799. err: err,
  800. id: peerInfo.ID(),
  801. isIncompatible: true,
  802. }
  803. }
  804. return peerInfo, peerKey, nil
  805. }
  806. func (sw *Switch) filterPeer(p Peer) error {
  807. // Avoid duplicate
  808. if sw.peers.Has(p.ID()) {
  809. return ErrRejected{id: p.ID(), isDuplicate: true}
  810. }
  811. errc := make(chan error, len(sw.peerFilters))
  812. for _, f := range sw.peerFilters {
  813. go func(f PeerFilterFunc, p Peer, errc chan<- error) {
  814. errc <- f(sw.peers, p)
  815. }(f, p, errc)
  816. }
  817. for i := 0; i < cap(errc); i++ {
  818. select {
  819. case err := <-errc:
  820. if err != nil {
  821. return ErrRejected{id: p.ID(), err: err, isFiltered: true}
  822. }
  823. case <-time.After(sw.filterTimeout):
  824. return ErrFilterTimeout{}
  825. }
  826. }
  827. return nil
  828. }
  829. // filterConn filters a connection, rejecting it if this function errors.
  830. //
  831. // FIXME: This is only here for compatibility with the current Switch code. In
  832. // the new P2P stack, peer/connection filtering should be moved into the Router
  833. // or PeerManager and removed from here.
  834. func (sw *Switch) filterConn(conn net.Conn) error {
  835. if sw.conns.Has(conn) {
  836. return ErrRejected{conn: conn, isDuplicate: true}
  837. }
  838. host, _, err := net.SplitHostPort(conn.RemoteAddr().String())
  839. if err != nil {
  840. return err
  841. }
  842. ip := net.ParseIP(host)
  843. if ip == nil {
  844. return fmt.Errorf("connection address has invalid IP address %q", host)
  845. }
  846. // Apply filter callbacks.
  847. chErr := make(chan error, len(sw.connFilters))
  848. for _, connFilter := range sw.connFilters {
  849. go func(connFilter ConnFilterFunc) {
  850. chErr <- connFilter(sw.conns, conn, []net.IP{ip})
  851. }(connFilter)
  852. }
  853. for i := 0; i < cap(chErr); i++ {
  854. select {
  855. case err := <-chErr:
  856. if err != nil {
  857. return ErrRejected{conn: conn, err: err, isFiltered: true}
  858. }
  859. case <-time.After(sw.filterTimeout):
  860. return ErrFilterTimeout{}
  861. }
  862. }
  863. // FIXME: Doesn't really make sense to set this here, but we preserve the
  864. // behavior from the previous P2P transport implementation.
  865. sw.conns.Set(conn, []net.IP{ip})
  866. return nil
  867. }
  868. // addPeer starts up the Peer and adds it to the Switch. Error is returned if
  869. // the peer is filtered out or failed to start or can't be added.
  870. func (sw *Switch) addPeer(p Peer) error {
  871. if err := sw.filterPeer(p); err != nil {
  872. return err
  873. }
  874. p.SetLogger(sw.Logger.With("peer", p.SocketAddr()))
  875. // Handle the shut down case where the switch has stopped but we're
  876. // concurrently trying to add a peer.
  877. if !sw.IsRunning() {
  878. // XXX should this return an error or just log and terminate?
  879. sw.Logger.Error("Won't start a peer - switch is not running", "peer", p)
  880. return nil
  881. }
  882. // Add some data to the peer, which is required by reactors.
  883. for _, reactor := range sw.reactors {
  884. p = reactor.InitPeer(p)
  885. }
  886. // Start the peer's send/recv routines.
  887. // Must start it before adding it to the peer set
  888. // to prevent Start and Stop from being called concurrently.
  889. err := p.Start()
  890. if err != nil {
  891. // Should never happen
  892. sw.Logger.Error("Error starting peer", "err", err, "peer", p)
  893. return err
  894. }
  895. // Add the peer to PeerSet. Do this before starting the reactors
  896. // so that if Receive errors, we will find the peer and remove it.
  897. // Add should not err since we already checked peers.Has().
  898. if err := sw.peers.Add(p); err != nil {
  899. return err
  900. }
  901. sw.metrics.Peers.Add(float64(1))
  902. // Start all the reactor protocols on the peer.
  903. for _, reactor := range sw.reactors {
  904. reactor.AddPeer(p)
  905. }
  906. sw.Logger.Info("Added peer", "peer", p)
  907. return nil
  908. }
  909. // NewNetAddressStrings returns an array of NetAddress'es build using
  910. // the provided strings.
  911. func NewNetAddressStrings(addrs []string) ([]*NetAddress, []error) {
  912. netAddrs := make([]*NetAddress, 0)
  913. errs := make([]error, 0)
  914. for _, addr := range addrs {
  915. netAddr, err := types.NewNetAddressString(addr)
  916. if err != nil {
  917. errs = append(errs, err)
  918. } else {
  919. netAddrs = append(netAddrs, netAddr)
  920. }
  921. }
  922. return netAddrs, errs
  923. }