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.

1065 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 sw.reconnecting.Has(string(addr.ID)) {
  372. return
  373. }
  374. sw.reconnecting.Set(string(addr.ID), addr)
  375. defer sw.reconnecting.Delete(string(addr.ID))
  376. start := time.Now()
  377. sw.Logger.Info("Reconnecting to peer", "addr", addr)
  378. for i := 0; i < reconnectAttempts; i++ {
  379. if !sw.IsRunning() {
  380. return
  381. }
  382. err := sw.DialPeerWithAddress(addr)
  383. if err == nil {
  384. return // success
  385. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  386. return
  387. }
  388. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  389. // sleep a set amount
  390. sw.randomSleep(reconnectInterval)
  391. continue
  392. }
  393. sw.Logger.Error("Failed to reconnect to peer. Beginning exponential backoff",
  394. "addr", addr, "elapsed", time.Since(start))
  395. for i := 0; i < reconnectBackOffAttempts; i++ {
  396. if !sw.IsRunning() {
  397. return
  398. }
  399. // sleep an exponentially increasing amount
  400. sleepIntervalSeconds := math.Pow(reconnectBackOffBaseSeconds, float64(i))
  401. sw.randomSleep(time.Duration(sleepIntervalSeconds) * time.Second)
  402. err := sw.DialPeerWithAddress(addr)
  403. if err == nil {
  404. return // success
  405. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  406. return
  407. }
  408. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  409. }
  410. sw.Logger.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start))
  411. }
  412. // SetAddrBook allows to set address book on Switch.
  413. func (sw *Switch) SetAddrBook(addrBook AddrBook) {
  414. sw.addrBook = addrBook
  415. }
  416. // MarkPeerAsGood marks the given peer as good when it did something useful
  417. // like contributed to consensus.
  418. func (sw *Switch) MarkPeerAsGood(peer Peer) {
  419. if sw.addrBook != nil {
  420. sw.addrBook.MarkGood(peer.ID())
  421. }
  422. }
  423. //---------------------------------------------------------------------
  424. // Dialing
  425. type privateAddr interface {
  426. PrivateAddr() bool
  427. }
  428. func isPrivateAddr(err error) bool {
  429. te, ok := err.(privateAddr)
  430. return ok && te.PrivateAddr()
  431. }
  432. // DialPeersAsync dials a list of peers asynchronously in random order.
  433. // Used to dial peers from config on startup or from unsafe-RPC (trusted sources).
  434. // It ignores ErrNetAddressLookup. However, if there are other errors, first
  435. // encounter is returned.
  436. // Nop if there are no peers.
  437. func (sw *Switch) DialPeersAsync(peers []string) error {
  438. netAddrs, errs := NewNetAddressStrings(peers)
  439. // report all the errors
  440. for _, err := range errs {
  441. sw.Logger.Error("Error in peer's address", "err", err)
  442. }
  443. // return first non-ErrNetAddressLookup error
  444. for _, err := range errs {
  445. if _, ok := err.(types.ErrNetAddressLookup); ok {
  446. continue
  447. }
  448. return err
  449. }
  450. sw.dialPeersAsync(netAddrs)
  451. return nil
  452. }
  453. func (sw *Switch) dialPeersAsync(netAddrs []*NetAddress) {
  454. ourAddr := sw.NetAddress()
  455. // TODO: this code feels like it's in the wrong place.
  456. // The integration tests depend on the addrBook being saved
  457. // right away but maybe we can change that. Recall that
  458. // the addrBook is only written to disk every 2min
  459. if sw.addrBook != nil {
  460. // add peers to `addrBook`
  461. for _, netAddr := range netAddrs {
  462. // do not add our address or ID
  463. if !netAddr.Same(ourAddr) {
  464. if err := sw.addrBook.AddAddress(netAddr, ourAddr); err != nil {
  465. if isPrivateAddr(err) {
  466. sw.Logger.Debug("Won't add peer's address to addrbook", "err", err)
  467. } else {
  468. sw.Logger.Error("Can't add peer's address to addrbook", "err", err)
  469. }
  470. }
  471. }
  472. }
  473. // Persist some peers to disk right away.
  474. // NOTE: integration tests depend on this
  475. sw.addrBook.Save()
  476. }
  477. // permute the list, dial them in random order.
  478. perm := mrand.Perm(len(netAddrs))
  479. for i := 0; i < len(perm); i++ {
  480. go func(i int) {
  481. j := perm[i]
  482. addr := netAddrs[j]
  483. if addr.Same(ourAddr) {
  484. sw.Logger.Debug("Ignore attempt to connect to ourselves", "addr", addr, "ourAddr", ourAddr)
  485. return
  486. }
  487. sw.randomSleep(0)
  488. err := sw.DialPeerWithAddress(addr)
  489. if err != nil {
  490. switch err.(type) {
  491. case ErrSwitchConnectToSelf, ErrSwitchDuplicatePeerID, ErrCurrentlyDialingOrExistingAddress:
  492. sw.Logger.Debug("Error dialing peer", "err", err)
  493. default:
  494. sw.Logger.Error("Error dialing peer", "err", err)
  495. }
  496. }
  497. }(i)
  498. }
  499. }
  500. // DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects
  501. // and authenticates successfully.
  502. // If we're currently dialing this address or it belongs to an existing peer,
  503. // ErrCurrentlyDialingOrExistingAddress is returned.
  504. func (sw *Switch) DialPeerWithAddress(addr *NetAddress) error {
  505. if sw.IsDialingOrExistingAddress(addr) {
  506. return ErrCurrentlyDialingOrExistingAddress{addr.String()}
  507. }
  508. sw.dialing.Set(string(addr.ID), addr)
  509. defer sw.dialing.Delete(string(addr.ID))
  510. return sw.addOutboundPeerWithConfig(addr, sw.config)
  511. }
  512. // sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds]
  513. func (sw *Switch) randomSleep(interval time.Duration) {
  514. // nolint:gosec // G404: Use of weak random number generator
  515. r := time.Duration(mrand.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond
  516. time.Sleep(r + interval)
  517. }
  518. // IsDialingOrExistingAddress returns true if switch has a peer with the given
  519. // address or dialing it at the moment.
  520. func (sw *Switch) IsDialingOrExistingAddress(addr *NetAddress) bool {
  521. return sw.dialing.Has(string(addr.ID)) ||
  522. sw.peers.Has(addr.ID) ||
  523. (!sw.config.AllowDuplicateIP && sw.peers.HasIP(addr.IP))
  524. }
  525. // AddPersistentPeers allows you to set persistent peers. It ignores
  526. // ErrNetAddressLookup. However, if there are other errors, first encounter is
  527. // returned.
  528. func (sw *Switch) AddPersistentPeers(addrs []string) error {
  529. sw.Logger.Info("Adding persistent peers", "addrs", addrs)
  530. netAddrs, errs := NewNetAddressStrings(addrs)
  531. // report all the errors
  532. for _, err := range errs {
  533. sw.Logger.Error("Error in peer's address", "err", err)
  534. }
  535. // return first non-ErrNetAddressLookup error
  536. for _, err := range errs {
  537. if _, ok := err.(types.ErrNetAddressLookup); ok {
  538. continue
  539. }
  540. return err
  541. }
  542. sw.persistentPeersAddrs = netAddrs
  543. return nil
  544. }
  545. func (sw *Switch) AddUnconditionalPeerIDs(ids []string) error {
  546. sw.Logger.Info("Adding unconditional peer ids", "ids", ids)
  547. for i, id := range ids {
  548. err := types.NodeID(id).Validate()
  549. if err != nil {
  550. return fmt.Errorf("wrong ID #%d: %w", i, err)
  551. }
  552. sw.unconditionalPeerIDs[types.NodeID(id)] = struct{}{}
  553. }
  554. return nil
  555. }
  556. func (sw *Switch) AddPrivatePeerIDs(ids []string) error {
  557. validIDs := make([]string, 0, len(ids))
  558. for i, id := range ids {
  559. err := types.NodeID(id).Validate()
  560. if err != nil {
  561. return fmt.Errorf("wrong ID #%d: %w", i, err)
  562. }
  563. validIDs = append(validIDs, id)
  564. }
  565. sw.addrBook.AddPrivateIDs(validIDs)
  566. return nil
  567. }
  568. func (sw *Switch) IsPeerPersistent(na *NetAddress) bool {
  569. for _, pa := range sw.persistentPeersAddrs {
  570. if pa.Equals(na) {
  571. return true
  572. }
  573. }
  574. return false
  575. }
  576. func (sw *Switch) acceptRoutine() {
  577. for {
  578. var peerNodeInfo types.NodeInfo
  579. c, err := sw.transport.Accept()
  580. if err == nil {
  581. // NOTE: The legacy MConn transport did handshaking in Accept(),
  582. // which was asynchronous and avoided head-of-line-blocking.
  583. // However, as handshakes are being migrated out from the transport,
  584. // we just do it synchronously here for now.
  585. peerNodeInfo, _, err = sw.handshakePeer(c, "")
  586. }
  587. if err == nil {
  588. err = sw.filterConn(c.(*mConnConnection).conn)
  589. }
  590. if err != nil {
  591. if c != nil {
  592. _ = c.Close()
  593. }
  594. if err == io.EOF {
  595. err = ErrTransportClosed{}
  596. }
  597. switch err := err.(type) {
  598. case ErrRejected:
  599. addr := err.Addr()
  600. if err.IsSelf() {
  601. // Remove the given address from the address book and add to our addresses
  602. // to avoid dialing in the future.
  603. sw.addrBook.RemoveAddress(&addr)
  604. sw.addrBook.AddOurAddress(&addr)
  605. }
  606. if err.IsIncompatible() {
  607. sw.addrBook.RemoveAddress(&addr)
  608. }
  609. sw.Logger.Info(
  610. "Inbound Peer rejected",
  611. "err", err,
  612. "numPeers", sw.peers.Size(),
  613. )
  614. continue
  615. case ErrFilterTimeout:
  616. sw.Logger.Error(
  617. "Peer filter timed out",
  618. "err", err,
  619. )
  620. continue
  621. case ErrTransportClosed:
  622. sw.Logger.Error(
  623. "Stopped accept routine, as transport is closed",
  624. "numPeers", sw.peers.Size(),
  625. )
  626. default:
  627. sw.Logger.Error(
  628. "Accept on transport errored",
  629. "err", err,
  630. "numPeers", sw.peers.Size(),
  631. )
  632. // We could instead have a retry loop around the acceptRoutine,
  633. // but that would need to stop and let the node shutdown eventually.
  634. // So might as well panic and let process managers restart the node.
  635. // There's no point in letting the node run without the acceptRoutine,
  636. // since it won't be able to accept new connections.
  637. panic(fmt.Errorf("accept routine exited: %v", err))
  638. }
  639. break
  640. }
  641. isPersistent := false
  642. addr, err := peerNodeInfo.NetAddress()
  643. if err == nil {
  644. isPersistent = sw.IsPeerPersistent(addr)
  645. }
  646. p := newPeer(
  647. peerNodeInfo,
  648. newPeerConn(false, isPersistent, c),
  649. sw.reactorsByCh,
  650. sw.StopPeerForError,
  651. PeerMetrics(sw.metrics),
  652. )
  653. if !sw.IsPeerUnconditional(p.NodeInfo().ID()) {
  654. // Ignore connection if we already have enough peers.
  655. _, in, _ := sw.NumPeers()
  656. if in >= sw.config.MaxNumInboundPeers {
  657. sw.Logger.Info(
  658. "Ignoring inbound connection: already have enough inbound peers",
  659. "address", p.SocketAddr(),
  660. "have", in,
  661. "max", sw.config.MaxNumInboundPeers,
  662. )
  663. _ = p.CloseConn()
  664. continue
  665. }
  666. }
  667. if err := sw.addPeer(p); err != nil {
  668. _ = p.CloseConn()
  669. if p.IsRunning() {
  670. _ = p.Stop()
  671. }
  672. sw.conns.RemoveAddr(p.RemoteAddr())
  673. sw.Logger.Info(
  674. "Ignoring inbound connection: error while adding peer",
  675. "err", err,
  676. "id", p.ID(),
  677. )
  678. }
  679. }
  680. }
  681. // dial the peer; make secret connection; authenticate against the dialed ID;
  682. // add the peer.
  683. // if dialing fails, start the reconnect loop. If handshake fails, it's over.
  684. // If peer is started successfully, reconnectLoop will start when
  685. // StopPeerForError is called.
  686. func (sw *Switch) addOutboundPeerWithConfig(
  687. addr *NetAddress,
  688. cfg *config.P2PConfig,
  689. ) error {
  690. sw.Logger.Info("Dialing peer", "address", addr)
  691. // XXX(xla): Remove the leakage of test concerns in implementation.
  692. if cfg.TestDialFail {
  693. go sw.reconnectToPeer(addr)
  694. return fmt.Errorf("dial err (peerConfig.DialFail == true)")
  695. }
  696. // Hardcoded timeout moved from MConn transport during refactoring.
  697. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  698. defer cancel()
  699. var peerNodeInfo types.NodeInfo
  700. c, err := sw.transport.Dial(ctx, Endpoint{
  701. Protocol: MConnProtocol,
  702. IP: addr.IP,
  703. Port: addr.Port,
  704. })
  705. if err == nil {
  706. peerNodeInfo, _, err = sw.handshakePeer(c, addr.ID)
  707. }
  708. if err == nil {
  709. err = sw.filterConn(c.(*mConnConnection).conn)
  710. }
  711. if err != nil {
  712. if c != nil {
  713. _ = c.Close()
  714. }
  715. if e, ok := err.(ErrRejected); ok {
  716. if e.IsSelf() {
  717. // Remove the given address from the address book and add to our addresses
  718. // to avoid dialing in the future.
  719. sw.addrBook.RemoveAddress(addr)
  720. sw.addrBook.AddOurAddress(addr)
  721. }
  722. if e.IsIncompatible() {
  723. sw.addrBook.RemoveAddress(addr)
  724. }
  725. return err
  726. }
  727. // retry persistent peers after
  728. // any dial error besides IsSelf()
  729. if sw.IsPeerPersistent(addr) {
  730. go sw.reconnectToPeer(addr)
  731. }
  732. return err
  733. }
  734. p := newPeer(
  735. peerNodeInfo,
  736. newPeerConn(true, sw.IsPeerPersistent(addr), c),
  737. sw.reactorsByCh,
  738. sw.StopPeerForError,
  739. PeerMetrics(sw.metrics),
  740. )
  741. if err := sw.addPeer(p); err != nil {
  742. _ = p.CloseConn()
  743. if p.IsRunning() {
  744. _ = p.Stop()
  745. }
  746. sw.conns.RemoveAddr(p.RemoteAddr())
  747. return err
  748. }
  749. return nil
  750. }
  751. func (sw *Switch) handshakePeer(
  752. c Connection,
  753. expectPeerID types.NodeID,
  754. ) (types.NodeInfo, crypto.PubKey, error) {
  755. // Moved from transport and hardcoded until legacy P2P stack removal.
  756. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  757. defer cancel()
  758. peerInfo, peerKey, err := c.Handshake(ctx, sw.nodeInfo, sw.nodeKey.PrivKey)
  759. if err != nil {
  760. return peerInfo, peerKey, ErrRejected{
  761. conn: c.(*mConnConnection).conn,
  762. err: fmt.Errorf("handshake failed: %v", err),
  763. isAuthFailure: true,
  764. }
  765. }
  766. if err = peerInfo.Validate(); err != nil {
  767. return peerInfo, peerKey, ErrRejected{
  768. conn: c.(*mConnConnection).conn,
  769. err: err,
  770. isNodeInfoInvalid: true,
  771. }
  772. }
  773. // For outgoing conns, ensure connection key matches dialed key.
  774. if expectPeerID != "" {
  775. peerID := types.NodeIDFromPubKey(peerKey)
  776. if expectPeerID != peerID {
  777. return peerInfo, peerKey, ErrRejected{
  778. conn: c.(*mConnConnection).conn,
  779. id: peerID,
  780. err: fmt.Errorf(
  781. "conn.ID (%v) dialed ID (%v) mismatch",
  782. peerID,
  783. expectPeerID,
  784. ),
  785. isAuthFailure: true,
  786. }
  787. }
  788. }
  789. if sw.nodeInfo.ID() == peerInfo.ID() {
  790. return peerInfo, peerKey, ErrRejected{
  791. addr: *types.NewNetAddress(peerInfo.ID(), c.(*mConnConnection).conn.RemoteAddr()),
  792. conn: c.(*mConnConnection).conn,
  793. id: peerInfo.ID(),
  794. isSelf: true,
  795. }
  796. }
  797. if err = sw.nodeInfo.CompatibleWith(peerInfo); err != nil {
  798. return peerInfo, peerKey, ErrRejected{
  799. conn: c.(*mConnConnection).conn,
  800. err: err,
  801. id: peerInfo.ID(),
  802. isIncompatible: true,
  803. }
  804. }
  805. return peerInfo, peerKey, nil
  806. }
  807. func (sw *Switch) filterPeer(p Peer) error {
  808. // Avoid duplicate
  809. if sw.peers.Has(p.ID()) {
  810. return ErrRejected{id: p.ID(), isDuplicate: true}
  811. }
  812. errc := make(chan error, len(sw.peerFilters))
  813. for _, f := range sw.peerFilters {
  814. go func(f PeerFilterFunc, p Peer, errc chan<- error) {
  815. errc <- f(sw.peers, p)
  816. }(f, p, errc)
  817. }
  818. for i := 0; i < cap(errc); i++ {
  819. select {
  820. case err := <-errc:
  821. if err != nil {
  822. return ErrRejected{id: p.ID(), err: err, isFiltered: true}
  823. }
  824. case <-time.After(sw.filterTimeout):
  825. return ErrFilterTimeout{}
  826. }
  827. }
  828. return nil
  829. }
  830. // filterConn filters a connection, rejecting it if this function errors.
  831. //
  832. // FIXME: This is only here for compatibility with the current Switch code. In
  833. // the new P2P stack, peer/connection filtering should be moved into the Router
  834. // or PeerManager and removed from here.
  835. func (sw *Switch) filterConn(conn net.Conn) error {
  836. if sw.conns.Has(conn) {
  837. return ErrRejected{conn: conn, isDuplicate: true}
  838. }
  839. host, _, err := net.SplitHostPort(conn.RemoteAddr().String())
  840. if err != nil {
  841. return err
  842. }
  843. ip := net.ParseIP(host)
  844. if ip == nil {
  845. return fmt.Errorf("connection address has invalid IP address %q", host)
  846. }
  847. // Apply filter callbacks.
  848. chErr := make(chan error, len(sw.connFilters))
  849. for _, connFilter := range sw.connFilters {
  850. go func(connFilter ConnFilterFunc) {
  851. chErr <- connFilter(sw.conns, conn, []net.IP{ip})
  852. }(connFilter)
  853. }
  854. for i := 0; i < cap(chErr); i++ {
  855. select {
  856. case err := <-chErr:
  857. if err != nil {
  858. return ErrRejected{conn: conn, err: err, isFiltered: true}
  859. }
  860. case <-time.After(sw.filterTimeout):
  861. return ErrFilterTimeout{}
  862. }
  863. }
  864. // FIXME: Doesn't really make sense to set this here, but we preserve the
  865. // behavior from the previous P2P transport implementation.
  866. sw.conns.Set(conn, []net.IP{ip})
  867. return nil
  868. }
  869. // addPeer starts up the Peer and adds it to the Switch. Error is returned if
  870. // the peer is filtered out or failed to start or can't be added.
  871. func (sw *Switch) addPeer(p Peer) error {
  872. if err := sw.filterPeer(p); err != nil {
  873. return err
  874. }
  875. p.SetLogger(sw.Logger.With("peer", p.SocketAddr()))
  876. // Handle the shut down case where the switch has stopped but we're
  877. // concurrently trying to add a peer.
  878. if !sw.IsRunning() {
  879. // XXX should this return an error or just log and terminate?
  880. sw.Logger.Error("Won't start a peer - switch is not running", "peer", p)
  881. return nil
  882. }
  883. // Add some data to the peer, which is required by reactors.
  884. for _, reactor := range sw.reactors {
  885. p = reactor.InitPeer(p)
  886. }
  887. // Start the peer's send/recv routines.
  888. // Must start it before adding it to the peer set
  889. // to prevent Start and Stop from being called concurrently.
  890. err := p.Start()
  891. if err != nil {
  892. // Should never happen
  893. sw.Logger.Error("Error starting peer", "err", err, "peer", p)
  894. return err
  895. }
  896. // Add the peer to PeerSet. Do this before starting the reactors
  897. // so that if Receive errors, we will find the peer and remove it.
  898. // Add should not err since we already checked peers.Has().
  899. if err := sw.peers.Add(p); err != nil {
  900. return err
  901. }
  902. sw.metrics.Peers.Add(float64(1))
  903. // Start all the reactor protocols on the peer.
  904. for _, reactor := range sw.reactors {
  905. reactor.AddPeer(p)
  906. }
  907. sw.Logger.Info("Added peer", "peer", p)
  908. return nil
  909. }
  910. // NewNetAddressStrings returns an array of NetAddress'es build using
  911. // the provided strings.
  912. func NewNetAddressStrings(addrs []string) ([]*NetAddress, []error) {
  913. netAddrs := make([]*NetAddress, 0)
  914. errs := make([]error, 0)
  915. for _, addr := range addrs {
  916. netAddr, err := types.NewNetAddressString(addr)
  917. if err != nil {
  918. errs = append(errs, err)
  919. } else {
  920. netAddrs = append(netAddrs, netAddr)
  921. }
  922. }
  923. return netAddrs, errs
  924. }