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.

1059 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 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 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. 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. addr := err.Addr()
  603. sw.addrBook.RemoveAddress(&addr)
  604. sw.addrBook.AddOurAddress(&addr)
  605. }
  606. sw.Logger.Info(
  607. "Inbound Peer rejected",
  608. "err", err,
  609. "numPeers", sw.peers.Size(),
  610. )
  611. continue
  612. case ErrFilterTimeout:
  613. sw.Logger.Error(
  614. "Peer filter timed out",
  615. "err", err,
  616. )
  617. continue
  618. case ErrTransportClosed:
  619. sw.Logger.Error(
  620. "Stopped accept routine, as transport is closed",
  621. "numPeers", sw.peers.Size(),
  622. )
  623. default:
  624. sw.Logger.Error(
  625. "Accept on transport errored",
  626. "err", err,
  627. "numPeers", sw.peers.Size(),
  628. )
  629. // We could instead have a retry loop around the acceptRoutine,
  630. // but that would need to stop and let the node shutdown eventually.
  631. // So might as well panic and let process managers restart the node.
  632. // There's no point in letting the node run without the acceptRoutine,
  633. // since it won't be able to accept new connections.
  634. panic(fmt.Errorf("accept routine exited: %v", err))
  635. }
  636. break
  637. }
  638. isPersistent := false
  639. addr, err := peerNodeInfo.NetAddress()
  640. if err == nil {
  641. isPersistent = sw.IsPeerPersistent(addr)
  642. }
  643. p := newPeer(
  644. peerNodeInfo,
  645. newPeerConn(false, isPersistent, c),
  646. sw.reactorsByCh,
  647. sw.StopPeerForError,
  648. PeerMetrics(sw.metrics),
  649. )
  650. if !sw.IsPeerUnconditional(p.NodeInfo().ID()) {
  651. // Ignore connection if we already have enough peers.
  652. _, in, _ := sw.NumPeers()
  653. if in >= sw.config.MaxNumInboundPeers {
  654. sw.Logger.Info(
  655. "Ignoring inbound connection: already have enough inbound peers",
  656. "address", p.SocketAddr(),
  657. "have", in,
  658. "max", sw.config.MaxNumInboundPeers,
  659. )
  660. _ = p.CloseConn()
  661. continue
  662. }
  663. }
  664. if err := sw.addPeer(p); err != nil {
  665. _ = p.CloseConn()
  666. if p.IsRunning() {
  667. _ = p.Stop()
  668. }
  669. sw.conns.RemoveAddr(p.RemoteAddr())
  670. sw.Logger.Info(
  671. "Ignoring inbound connection: error while adding peer",
  672. "err", err,
  673. "id", p.ID(),
  674. )
  675. }
  676. }
  677. }
  678. // dial the peer; make secret connection; authenticate against the dialed ID;
  679. // add the peer.
  680. // if dialing fails, start the reconnect loop. If handshake fails, it's over.
  681. // If peer is started successfully, reconnectLoop will start when
  682. // StopPeerForError is called.
  683. func (sw *Switch) addOutboundPeerWithConfig(
  684. addr *NetAddress,
  685. cfg *config.P2PConfig,
  686. ) error {
  687. sw.Logger.Info("Dialing peer", "address", addr)
  688. // XXX(xla): Remove the leakage of test concerns in implementation.
  689. if cfg.TestDialFail {
  690. go sw.reconnectToPeer(addr)
  691. return fmt.Errorf("dial err (peerConfig.DialFail == true)")
  692. }
  693. // Hardcoded timeout moved from MConn transport during refactoring.
  694. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  695. defer cancel()
  696. var peerNodeInfo types.NodeInfo
  697. c, err := sw.transport.Dial(ctx, Endpoint{
  698. Protocol: MConnProtocol,
  699. IP: addr.IP,
  700. Port: addr.Port,
  701. })
  702. if err == nil {
  703. peerNodeInfo, _, err = sw.handshakePeer(c, addr.ID)
  704. }
  705. if err == nil {
  706. err = sw.filterConn(c.(*mConnConnection).conn)
  707. }
  708. if err != nil {
  709. if c != nil {
  710. _ = c.Close()
  711. }
  712. if e, ok := err.(ErrRejected); ok {
  713. if e.IsSelf() {
  714. // Remove the given address from the address book and add to our addresses
  715. // to avoid dialing in the future.
  716. sw.addrBook.RemoveAddress(addr)
  717. sw.addrBook.AddOurAddress(addr)
  718. return err
  719. }
  720. }
  721. // retry persistent peers after
  722. // any dial error besides IsSelf()
  723. if sw.IsPeerPersistent(addr) {
  724. go sw.reconnectToPeer(addr)
  725. }
  726. return err
  727. }
  728. p := newPeer(
  729. peerNodeInfo,
  730. newPeerConn(true, sw.IsPeerPersistent(addr), c),
  731. sw.reactorsByCh,
  732. sw.StopPeerForError,
  733. PeerMetrics(sw.metrics),
  734. )
  735. if err := sw.addPeer(p); err != nil {
  736. _ = p.CloseConn()
  737. if p.IsRunning() {
  738. _ = p.Stop()
  739. }
  740. sw.conns.RemoveAddr(p.RemoteAddr())
  741. return err
  742. }
  743. return nil
  744. }
  745. func (sw *Switch) handshakePeer(
  746. c Connection,
  747. expectPeerID types.NodeID,
  748. ) (types.NodeInfo, crypto.PubKey, error) {
  749. // Moved from transport and hardcoded until legacy P2P stack removal.
  750. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  751. defer cancel()
  752. peerInfo, peerKey, err := c.Handshake(ctx, sw.nodeInfo, sw.nodeKey.PrivKey)
  753. if err != nil {
  754. return peerInfo, peerKey, ErrRejected{
  755. conn: c.(*mConnConnection).conn,
  756. err: fmt.Errorf("handshake failed: %v", err),
  757. isAuthFailure: true,
  758. }
  759. }
  760. if err = peerInfo.Validate(); err != nil {
  761. return peerInfo, peerKey, ErrRejected{
  762. conn: c.(*mConnConnection).conn,
  763. err: err,
  764. isNodeInfoInvalid: true,
  765. }
  766. }
  767. // For outgoing conns, ensure connection key matches dialed key.
  768. if expectPeerID != "" {
  769. peerID := types.NodeIDFromPubKey(peerKey)
  770. if expectPeerID != peerID {
  771. return peerInfo, peerKey, ErrRejected{
  772. conn: c.(*mConnConnection).conn,
  773. id: peerID,
  774. err: fmt.Errorf(
  775. "conn.ID (%v) dialed ID (%v) mismatch",
  776. peerID,
  777. expectPeerID,
  778. ),
  779. isAuthFailure: true,
  780. }
  781. }
  782. }
  783. if sw.nodeInfo.ID() == peerInfo.ID() {
  784. return peerInfo, peerKey, ErrRejected{
  785. addr: *types.NewNetAddress(peerInfo.ID(), c.(*mConnConnection).conn.RemoteAddr()),
  786. conn: c.(*mConnConnection).conn,
  787. id: peerInfo.ID(),
  788. isSelf: true,
  789. }
  790. }
  791. if err = sw.nodeInfo.CompatibleWith(peerInfo); err != nil {
  792. return peerInfo, peerKey, ErrRejected{
  793. conn: c.(*mConnConnection).conn,
  794. err: err,
  795. id: peerInfo.ID(),
  796. isIncompatible: true,
  797. }
  798. }
  799. return peerInfo, peerKey, nil
  800. }
  801. func (sw *Switch) filterPeer(p Peer) error {
  802. // Avoid duplicate
  803. if sw.peers.Has(p.ID()) {
  804. return ErrRejected{id: p.ID(), isDuplicate: true}
  805. }
  806. errc := make(chan error, len(sw.peerFilters))
  807. for _, f := range sw.peerFilters {
  808. go func(f PeerFilterFunc, p Peer, errc chan<- error) {
  809. errc <- f(sw.peers, p)
  810. }(f, p, errc)
  811. }
  812. for i := 0; i < cap(errc); i++ {
  813. select {
  814. case err := <-errc:
  815. if err != nil {
  816. return ErrRejected{id: p.ID(), err: err, isFiltered: true}
  817. }
  818. case <-time.After(sw.filterTimeout):
  819. return ErrFilterTimeout{}
  820. }
  821. }
  822. return nil
  823. }
  824. // filterConn filters a connection, rejecting it if this function errors.
  825. //
  826. // FIXME: This is only here for compatibility with the current Switch code. In
  827. // the new P2P stack, peer/connection filtering should be moved into the Router
  828. // or PeerManager and removed from here.
  829. func (sw *Switch) filterConn(conn net.Conn) error {
  830. if sw.conns.Has(conn) {
  831. return ErrRejected{conn: conn, isDuplicate: true}
  832. }
  833. host, _, err := net.SplitHostPort(conn.RemoteAddr().String())
  834. if err != nil {
  835. return err
  836. }
  837. ip := net.ParseIP(host)
  838. if ip == nil {
  839. return fmt.Errorf("connection address has invalid IP address %q", host)
  840. }
  841. // Apply filter callbacks.
  842. chErr := make(chan error, len(sw.connFilters))
  843. for _, connFilter := range sw.connFilters {
  844. go func(connFilter ConnFilterFunc) {
  845. chErr <- connFilter(sw.conns, conn, []net.IP{ip})
  846. }(connFilter)
  847. }
  848. for i := 0; i < cap(chErr); i++ {
  849. select {
  850. case err := <-chErr:
  851. if err != nil {
  852. return ErrRejected{conn: conn, err: err, isFiltered: true}
  853. }
  854. case <-time.After(sw.filterTimeout):
  855. return ErrFilterTimeout{}
  856. }
  857. }
  858. // FIXME: Doesn't really make sense to set this here, but we preserve the
  859. // behavior from the previous P2P transport implementation.
  860. sw.conns.Set(conn, []net.IP{ip})
  861. return nil
  862. }
  863. // addPeer starts up the Peer and adds it to the Switch. Error is returned if
  864. // the peer is filtered out or failed to start or can't be added.
  865. func (sw *Switch) addPeer(p Peer) error {
  866. if err := sw.filterPeer(p); err != nil {
  867. return err
  868. }
  869. p.SetLogger(sw.Logger.With("peer", p.SocketAddr()))
  870. // Handle the shut down case where the switch has stopped but we're
  871. // concurrently trying to add a peer.
  872. if !sw.IsRunning() {
  873. // XXX should this return an error or just log and terminate?
  874. sw.Logger.Error("Won't start a peer - switch is not running", "peer", p)
  875. return nil
  876. }
  877. // Add some data to the peer, which is required by reactors.
  878. for _, reactor := range sw.reactors {
  879. p = reactor.InitPeer(p)
  880. }
  881. // Start the peer's send/recv routines.
  882. // Must start it before adding it to the peer set
  883. // to prevent Start and Stop from being called concurrently.
  884. err := p.Start()
  885. if err != nil {
  886. // Should never happen
  887. sw.Logger.Error("Error starting peer", "err", err, "peer", p)
  888. return err
  889. }
  890. // Add the peer to PeerSet. Do this before starting the reactors
  891. // so that if Receive errors, we will find the peer and remove it.
  892. // Add should not err since we already checked peers.Has().
  893. if err := sw.peers.Add(p); err != nil {
  894. return err
  895. }
  896. sw.metrics.Peers.Add(float64(1))
  897. // Start all the reactor protocols on the peer.
  898. for _, reactor := range sw.reactors {
  899. reactor.AddPeer(p)
  900. }
  901. sw.Logger.Info("Added peer", "peer", p)
  902. return nil
  903. }
  904. // NewNetAddressStrings returns an array of NetAddress'es build using
  905. // the provided strings.
  906. func NewNetAddressStrings(addrs []string) ([]*NetAddress, []error) {
  907. netAddrs := make([]*NetAddress, 0)
  908. errs := make([]error, 0)
  909. for _, addr := range addrs {
  910. netAddr, err := types.NewNetAddressString(addr)
  911. if err != nil {
  912. errs = append(errs, err)
  913. } else {
  914. netAddrs = append(netAddrs, netAddr)
  915. }
  916. }
  917. return netAddrs, errs
  918. }