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.

860 lines
24 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: 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: 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. "math"
  6. "sync"
  7. "time"
  8. "github.com/tendermint/tendermint/config"
  9. "github.com/tendermint/tendermint/libs/cmap"
  10. "github.com/tendermint/tendermint/libs/rand"
  11. "github.com/tendermint/tendermint/libs/service"
  12. "github.com/tendermint/tendermint/p2p/conn"
  13. )
  14. const (
  15. // wait a random amount of time from this interval
  16. // before dialing peers or reconnecting to help prevent DoS
  17. dialRandomizerIntervalMilliseconds = 3000
  18. // repeatedly try to reconnect for a few minutes
  19. // ie. 5 * 20 = 100s
  20. reconnectAttempts = 20
  21. reconnectInterval = 5 * time.Second
  22. // then move into exponential backoff mode for ~1day
  23. // ie. 3**10 = 16hrs
  24. reconnectBackOffAttempts = 10
  25. reconnectBackOffBaseSeconds = 3
  26. )
  27. // MConnConfig returns an MConnConfig with fields updated
  28. // from the P2PConfig.
  29. func MConnConfig(cfg *config.P2PConfig) conn.MConnConfig {
  30. mConfig := conn.DefaultMConnConfig()
  31. mConfig.FlushThrottle = cfg.FlushThrottleTimeout
  32. mConfig.SendRate = cfg.SendRate
  33. mConfig.RecvRate = cfg.RecvRate
  34. mConfig.MaxPacketMsgPayloadSize = cfg.MaxPacketMsgPayloadSize
  35. return mConfig
  36. }
  37. //-----------------------------------------------------------------------------
  38. // An AddrBook represents an address book from the pex package, which is used
  39. // to store peer addresses.
  40. type AddrBook interface {
  41. AddAddress(addr *NetAddress, src *NetAddress) error
  42. AddPrivateIDs([]string)
  43. AddOurAddress(*NetAddress)
  44. OurAddress(*NetAddress) bool
  45. MarkGood(NodeID)
  46. RemoveAddress(*NetAddress)
  47. HasAddress(*NetAddress) bool
  48. Save()
  49. }
  50. // PeerFilterFunc to be implemented by filter hooks after a new Peer has been
  51. // fully setup.
  52. type PeerFilterFunc func(IPeerSet, Peer) error
  53. //-----------------------------------------------------------------------------
  54. // Switch handles peer connections and exposes an API to receive incoming messages
  55. // on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one
  56. // or more `Channels`. So while sending outgoing messages is typically performed on the peer,
  57. // incoming messages are received on the reactor.
  58. type Switch struct {
  59. service.BaseService
  60. config *config.P2PConfig
  61. reactors map[string]Reactor
  62. chDescs []*conn.ChannelDescriptor
  63. reactorsByCh map[byte]Reactor
  64. peers *PeerSet
  65. dialing *cmap.CMap
  66. reconnecting *cmap.CMap
  67. nodeInfo NodeInfo // our node info
  68. nodeKey NodeKey // our node privkey
  69. addrBook AddrBook
  70. // peers addresses with whom we'll maintain constant connection
  71. persistentPeersAddrs []*NetAddress
  72. unconditionalPeerIDs map[NodeID]struct{}
  73. transport Transport
  74. filterTimeout time.Duration
  75. peerFilters []PeerFilterFunc
  76. rng *rand.Rand // seed for randomizing dial times and orders
  77. metrics *Metrics
  78. }
  79. // NetAddress returns the first address the switch is listening on,
  80. // or nil if no addresses are found.
  81. func (sw *Switch) NetAddress() *NetAddress {
  82. endpoints := sw.transport.Endpoints()
  83. if len(endpoints) == 0 {
  84. return nil
  85. }
  86. return endpoints[0].NetAddress()
  87. }
  88. // SwitchOption sets an optional parameter on the Switch.
  89. type SwitchOption func(*Switch)
  90. // NewSwitch creates a new Switch with the given config.
  91. func NewSwitch(
  92. cfg *config.P2PConfig,
  93. transport Transport,
  94. options ...SwitchOption,
  95. ) *Switch {
  96. sw := &Switch{
  97. config: cfg,
  98. reactors: make(map[string]Reactor),
  99. chDescs: make([]*conn.ChannelDescriptor, 0),
  100. reactorsByCh: make(map[byte]Reactor),
  101. peers: NewPeerSet(),
  102. dialing: cmap.NewCMap(),
  103. reconnecting: cmap.NewCMap(),
  104. metrics: NopMetrics(),
  105. transport: transport,
  106. filterTimeout: defaultFilterTimeout,
  107. persistentPeersAddrs: make([]*NetAddress, 0),
  108. unconditionalPeerIDs: make(map[NodeID]struct{}),
  109. }
  110. // Ensure we have a completely undeterministic PRNG.
  111. sw.rng = rand.NewRand()
  112. sw.BaseService = *service.NewBaseService(nil, "P2P Switch", sw)
  113. for _, option := range options {
  114. option(sw)
  115. }
  116. return sw
  117. }
  118. // SwitchFilterTimeout sets the timeout used for peer filters.
  119. func SwitchFilterTimeout(timeout time.Duration) SwitchOption {
  120. return func(sw *Switch) { sw.filterTimeout = timeout }
  121. }
  122. // SwitchPeerFilters sets the filters for rejection of new peers.
  123. func SwitchPeerFilters(filters ...PeerFilterFunc) SwitchOption {
  124. return func(sw *Switch) { sw.peerFilters = filters }
  125. }
  126. // WithMetrics sets the metrics.
  127. func WithMetrics(metrics *Metrics) SwitchOption {
  128. return func(sw *Switch) { sw.metrics = metrics }
  129. }
  130. //---------------------------------------------------------------------
  131. // Switch setup
  132. // AddReactor adds the given reactor to the switch.
  133. // NOTE: Not goroutine safe.
  134. func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor {
  135. for _, chDesc := range reactor.GetChannels() {
  136. chID := chDesc.ID
  137. // No two reactors can share the same channel.
  138. if sw.reactorsByCh[chID] != nil {
  139. panic(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor))
  140. }
  141. sw.chDescs = append(sw.chDescs, chDesc)
  142. sw.reactorsByCh[chID] = reactor
  143. }
  144. sw.reactors[name] = reactor
  145. reactor.SetSwitch(sw)
  146. return reactor
  147. }
  148. // RemoveReactor removes the given Reactor from the Switch.
  149. // NOTE: Not goroutine safe.
  150. func (sw *Switch) RemoveReactor(name string, reactor Reactor) {
  151. for _, chDesc := range reactor.GetChannels() {
  152. // remove channel description
  153. for i := 0; i < len(sw.chDescs); i++ {
  154. if chDesc.ID == sw.chDescs[i].ID {
  155. sw.chDescs = append(sw.chDescs[:i], sw.chDescs[i+1:]...)
  156. break
  157. }
  158. }
  159. delete(sw.reactorsByCh, chDesc.ID)
  160. }
  161. delete(sw.reactors, name)
  162. reactor.SetSwitch(nil)
  163. }
  164. // Reactors returns a map of reactors registered on the switch.
  165. // NOTE: Not goroutine safe.
  166. func (sw *Switch) Reactors() map[string]Reactor {
  167. return sw.reactors
  168. }
  169. // Reactor returns the reactor with the given name.
  170. // NOTE: Not goroutine safe.
  171. func (sw *Switch) Reactor(name string) Reactor {
  172. return sw.reactors[name]
  173. }
  174. // SetNodeInfo sets the switch's NodeInfo for checking compatibility and handshaking with other nodes.
  175. // NOTE: Not goroutine safe.
  176. func (sw *Switch) SetNodeInfo(nodeInfo NodeInfo) {
  177. sw.nodeInfo = nodeInfo
  178. }
  179. // NodeInfo returns the switch's NodeInfo.
  180. // NOTE: Not goroutine safe.
  181. func (sw *Switch) NodeInfo() NodeInfo {
  182. return sw.nodeInfo
  183. }
  184. // SetNodeKey sets the switch's private key for authenticated encryption.
  185. // NOTE: Not goroutine safe.
  186. func (sw *Switch) SetNodeKey(nodeKey NodeKey) {
  187. sw.nodeKey = nodeKey
  188. }
  189. //---------------------------------------------------------------------
  190. // Service start/stop
  191. // OnStart implements BaseService. It starts all the reactors and peers.
  192. func (sw *Switch) OnStart() error {
  193. // FIXME: Temporary hack to pass channel descriptors to MConn transport,
  194. // since they are not available when it is constructed. This will be
  195. // fixed when we implement the new router abstraction.
  196. sw.transport.SetChannelDescriptors(sw.chDescs)
  197. // Start reactors
  198. for _, reactor := range sw.reactors {
  199. err := reactor.Start()
  200. if err != nil {
  201. return fmt.Errorf("failed to start %v: %w", reactor, err)
  202. }
  203. }
  204. // Start accepting Peers.
  205. go sw.acceptRoutine()
  206. return nil
  207. }
  208. // OnStop implements BaseService. It stops all peers and reactors.
  209. func (sw *Switch) OnStop() {
  210. // Stop peers
  211. for _, p := range sw.peers.List() {
  212. sw.stopAndRemovePeer(p, nil)
  213. }
  214. // Stop reactors
  215. sw.Logger.Debug("Switch: Stopping reactors")
  216. for _, reactor := range sw.reactors {
  217. if err := reactor.Stop(); err != nil {
  218. sw.Logger.Error("error while stopping reactor", "reactor", reactor, "error", err)
  219. }
  220. }
  221. }
  222. //---------------------------------------------------------------------
  223. // Peers
  224. // Broadcast runs a go routine for each attempted send, which will block trying
  225. // to send for defaultSendTimeoutSeconds. Returns a channel which receives
  226. // success values for each attempted send (false if times out). Channel will be
  227. // closed once msg bytes are sent to all peers (or time out).
  228. //
  229. // NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved.
  230. func (sw *Switch) Broadcast(chID byte, msgBytes []byte) chan bool {
  231. sw.Logger.Debug("Broadcast", "channel", chID, "msgBytes", msgBytes)
  232. peers := sw.peers.List()
  233. var wg sync.WaitGroup
  234. wg.Add(len(peers))
  235. successChan := make(chan bool, len(peers))
  236. for _, peer := range peers {
  237. go func(p Peer) {
  238. defer wg.Done()
  239. success := p.Send(chID, msgBytes)
  240. successChan <- success
  241. }(peer)
  242. }
  243. go func() {
  244. wg.Wait()
  245. close(successChan)
  246. }()
  247. return successChan
  248. }
  249. // NumPeers returns the count of outbound/inbound and outbound-dialing peers.
  250. // unconditional peers are not counted here.
  251. func (sw *Switch) NumPeers() (outbound, inbound, dialing int) {
  252. peers := sw.peers.List()
  253. for _, peer := range peers {
  254. if peer.IsOutbound() {
  255. if !sw.IsPeerUnconditional(peer.ID()) {
  256. outbound++
  257. }
  258. } else {
  259. if !sw.IsPeerUnconditional(peer.ID()) {
  260. inbound++
  261. }
  262. }
  263. }
  264. dialing = sw.dialing.Size()
  265. return
  266. }
  267. func (sw *Switch) IsPeerUnconditional(id NodeID) bool {
  268. _, ok := sw.unconditionalPeerIDs[id]
  269. return ok
  270. }
  271. // MaxNumOutboundPeers returns a maximum number of outbound peers.
  272. func (sw *Switch) MaxNumOutboundPeers() int {
  273. return sw.config.MaxNumOutboundPeers
  274. }
  275. // Peers returns the set of peers that are connected to the switch.
  276. func (sw *Switch) Peers() IPeerSet {
  277. return sw.peers
  278. }
  279. // StopPeerForError disconnects from a peer due to external error.
  280. // If the peer is persistent, it will attempt to reconnect.
  281. // TODO: make record depending on reason.
  282. func (sw *Switch) StopPeerForError(peer Peer, reason interface{}) {
  283. if !peer.IsRunning() {
  284. return
  285. }
  286. sw.Logger.Error("Stopping peer for error", "peer", peer, "err", reason)
  287. sw.stopAndRemovePeer(peer, reason)
  288. if peer.IsPersistent() {
  289. var addr *NetAddress
  290. if peer.IsOutbound() { // socket address for outbound peers
  291. addr = peer.SocketAddr()
  292. } else { // self-reported address for inbound peers
  293. var err error
  294. addr, err = peer.NodeInfo().NetAddress()
  295. if err != nil {
  296. sw.Logger.Error("Wanted to reconnect to inbound peer, but self-reported address is wrong",
  297. "peer", peer, "err", err)
  298. return
  299. }
  300. }
  301. go sw.reconnectToPeer(addr)
  302. }
  303. }
  304. // StopPeerGracefully disconnects from a peer gracefully.
  305. // TODO: handle graceful disconnects.
  306. func (sw *Switch) StopPeerGracefully(peer Peer) {
  307. sw.Logger.Info("Stopping peer gracefully")
  308. sw.stopAndRemovePeer(peer, nil)
  309. }
  310. func (sw *Switch) stopAndRemovePeer(peer Peer, reason interface{}) {
  311. if err := peer.Stop(); err != nil {
  312. sw.Logger.Error("error while stopping peer", "error", err) // TODO: should return error to be handled accordingly
  313. }
  314. for _, reactor := range sw.reactors {
  315. reactor.RemovePeer(peer, reason)
  316. }
  317. // Removing a peer should go last to avoid a situation where a peer
  318. // reconnect to our node and the switch calls InitPeer before
  319. // RemovePeer is finished.
  320. // https://github.com/tendermint/tendermint/issues/3338
  321. if sw.peers.Remove(peer) {
  322. sw.metrics.Peers.Add(float64(-1))
  323. }
  324. }
  325. // reconnectToPeer tries to reconnect to the addr, first repeatedly
  326. // with a fixed interval, then with exponential backoff.
  327. // If no success after all that, it stops trying, and leaves it
  328. // to the PEX/Addrbook to find the peer with the addr again
  329. // NOTE: this will keep trying even if the handshake or auth fails.
  330. // TODO: be more explicit with error types so we only retry on certain failures
  331. // - ie. if we're getting ErrDuplicatePeer we can stop
  332. // because the addrbook got us the peer back already
  333. func (sw *Switch) reconnectToPeer(addr *NetAddress) {
  334. if sw.reconnecting.Has(string(addr.ID)) {
  335. return
  336. }
  337. sw.reconnecting.Set(string(addr.ID), addr)
  338. defer sw.reconnecting.Delete(string(addr.ID))
  339. start := time.Now()
  340. sw.Logger.Info("Reconnecting to peer", "addr", addr)
  341. for i := 0; i < reconnectAttempts; i++ {
  342. if !sw.IsRunning() {
  343. return
  344. }
  345. err := sw.DialPeerWithAddress(addr)
  346. if err == nil {
  347. return // success
  348. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  349. return
  350. }
  351. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  352. // sleep a set amount
  353. sw.randomSleep(reconnectInterval)
  354. continue
  355. }
  356. sw.Logger.Error("Failed to reconnect to peer. Beginning exponential backoff",
  357. "addr", addr, "elapsed", time.Since(start))
  358. for i := 0; i < reconnectBackOffAttempts; i++ {
  359. if !sw.IsRunning() {
  360. return
  361. }
  362. // sleep an exponentially increasing amount
  363. sleepIntervalSeconds := math.Pow(reconnectBackOffBaseSeconds, float64(i))
  364. sw.randomSleep(time.Duration(sleepIntervalSeconds) * time.Second)
  365. err := sw.DialPeerWithAddress(addr)
  366. if err == nil {
  367. return // success
  368. } else if _, ok := err.(ErrCurrentlyDialingOrExistingAddress); ok {
  369. return
  370. }
  371. sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "err", err, "addr", addr)
  372. }
  373. sw.Logger.Error("Failed to reconnect to peer. Giving up", "addr", addr, "elapsed", time.Since(start))
  374. }
  375. // SetAddrBook allows to set address book on Switch.
  376. func (sw *Switch) SetAddrBook(addrBook AddrBook) {
  377. sw.addrBook = addrBook
  378. }
  379. // MarkPeerAsGood marks the given peer as good when it did something useful
  380. // like contributed to consensus.
  381. func (sw *Switch) MarkPeerAsGood(peer Peer) {
  382. if sw.addrBook != nil {
  383. sw.addrBook.MarkGood(peer.ID())
  384. }
  385. }
  386. //---------------------------------------------------------------------
  387. // Dialing
  388. type privateAddr interface {
  389. PrivateAddr() bool
  390. }
  391. func isPrivateAddr(err error) bool {
  392. te, ok := err.(privateAddr)
  393. return ok && te.PrivateAddr()
  394. }
  395. // DialPeersAsync dials a list of peers asynchronously in random order.
  396. // Used to dial peers from config on startup or from unsafe-RPC (trusted sources).
  397. // It ignores ErrNetAddressLookup. However, if there are other errors, first
  398. // encounter is returned.
  399. // Nop if there are no peers.
  400. func (sw *Switch) DialPeersAsync(peers []string) error {
  401. netAddrs, errs := NewNetAddressStrings(peers)
  402. // report all the errors
  403. for _, err := range errs {
  404. sw.Logger.Error("Error in peer's address", "err", err)
  405. }
  406. // return first non-ErrNetAddressLookup error
  407. for _, err := range errs {
  408. if _, ok := err.(ErrNetAddressLookup); ok {
  409. continue
  410. }
  411. return err
  412. }
  413. sw.dialPeersAsync(netAddrs)
  414. return nil
  415. }
  416. func (sw *Switch) dialPeersAsync(netAddrs []*NetAddress) {
  417. ourAddr := sw.NetAddress()
  418. // TODO: this code feels like it's in the wrong place.
  419. // The integration tests depend on the addrBook being saved
  420. // right away but maybe we can change that. Recall that
  421. // the addrBook is only written to disk every 2min
  422. if sw.addrBook != nil {
  423. // add peers to `addrBook`
  424. for _, netAddr := range netAddrs {
  425. // do not add our address or ID
  426. if !netAddr.Same(ourAddr) {
  427. if err := sw.addrBook.AddAddress(netAddr, ourAddr); err != nil {
  428. if isPrivateAddr(err) {
  429. sw.Logger.Debug("Won't add peer's address to addrbook", "err", err)
  430. } else {
  431. sw.Logger.Error("Can't add peer's address to addrbook", "err", err)
  432. }
  433. }
  434. }
  435. }
  436. // Persist some peers to disk right away.
  437. // NOTE: integration tests depend on this
  438. sw.addrBook.Save()
  439. }
  440. // permute the list, dial them in random order.
  441. perm := sw.rng.Perm(len(netAddrs))
  442. for i := 0; i < len(perm); i++ {
  443. go func(i int) {
  444. j := perm[i]
  445. addr := netAddrs[j]
  446. if addr.Same(ourAddr) {
  447. sw.Logger.Debug("Ignore attempt to connect to ourselves", "addr", addr, "ourAddr", ourAddr)
  448. return
  449. }
  450. sw.randomSleep(0)
  451. err := sw.DialPeerWithAddress(addr)
  452. if err != nil {
  453. switch err.(type) {
  454. case ErrSwitchConnectToSelf, ErrSwitchDuplicatePeerID, ErrCurrentlyDialingOrExistingAddress:
  455. sw.Logger.Debug("Error dialing peer", "err", err)
  456. default:
  457. sw.Logger.Error("Error dialing peer", "err", err)
  458. }
  459. }
  460. }(i)
  461. }
  462. }
  463. // DialPeerWithAddress dials the given peer and runs sw.addPeer if it connects
  464. // and authenticates successfully.
  465. // If we're currently dialing this address or it belongs to an existing peer,
  466. // ErrCurrentlyDialingOrExistingAddress is returned.
  467. func (sw *Switch) DialPeerWithAddress(addr *NetAddress) error {
  468. if sw.IsDialingOrExistingAddress(addr) {
  469. return ErrCurrentlyDialingOrExistingAddress{addr.String()}
  470. }
  471. sw.dialing.Set(string(addr.ID), addr)
  472. defer sw.dialing.Delete(string(addr.ID))
  473. return sw.addOutboundPeerWithConfig(addr, sw.config)
  474. }
  475. // sleep for interval plus some random amount of ms on [0, dialRandomizerIntervalMilliseconds]
  476. func (sw *Switch) randomSleep(interval time.Duration) {
  477. r := time.Duration(sw.rng.Int63n(dialRandomizerIntervalMilliseconds)) * time.Millisecond
  478. time.Sleep(r + interval)
  479. }
  480. // IsDialingOrExistingAddress returns true if switch has a peer with the given
  481. // address or dialing it at the moment.
  482. func (sw *Switch) IsDialingOrExistingAddress(addr *NetAddress) bool {
  483. return sw.dialing.Has(string(addr.ID)) ||
  484. sw.peers.Has(addr.ID) ||
  485. (!sw.config.AllowDuplicateIP && sw.peers.HasIP(addr.IP))
  486. }
  487. // AddPersistentPeers allows you to set persistent peers. It ignores
  488. // ErrNetAddressLookup. However, if there are other errors, first encounter is
  489. // returned.
  490. func (sw *Switch) AddPersistentPeers(addrs []string) error {
  491. sw.Logger.Info("Adding persistent peers", "addrs", addrs)
  492. netAddrs, errs := NewNetAddressStrings(addrs)
  493. // report all the errors
  494. for _, err := range errs {
  495. sw.Logger.Error("Error in peer's address", "err", err)
  496. }
  497. // return first non-ErrNetAddressLookup error
  498. for _, err := range errs {
  499. if _, ok := err.(ErrNetAddressLookup); ok {
  500. continue
  501. }
  502. return err
  503. }
  504. sw.persistentPeersAddrs = netAddrs
  505. return nil
  506. }
  507. func (sw *Switch) AddUnconditionalPeerIDs(ids []string) error {
  508. sw.Logger.Info("Adding unconditional peer ids", "ids", ids)
  509. for i, id := range ids {
  510. err := NodeID(id).Validate()
  511. if err != nil {
  512. return fmt.Errorf("wrong ID #%d: %w", i, err)
  513. }
  514. sw.unconditionalPeerIDs[NodeID(id)] = struct{}{}
  515. }
  516. return nil
  517. }
  518. func (sw *Switch) AddPrivatePeerIDs(ids []string) error {
  519. validIDs := make([]string, 0, len(ids))
  520. for i, id := range ids {
  521. err := NodeID(id).Validate()
  522. if err != nil {
  523. return fmt.Errorf("wrong ID #%d: %w", i, err)
  524. }
  525. validIDs = append(validIDs, id)
  526. }
  527. sw.addrBook.AddPrivateIDs(validIDs)
  528. return nil
  529. }
  530. func (sw *Switch) IsPeerPersistent(na *NetAddress) bool {
  531. for _, pa := range sw.persistentPeersAddrs {
  532. if pa.Equals(na) {
  533. return true
  534. }
  535. }
  536. return false
  537. }
  538. func (sw *Switch) acceptRoutine() {
  539. for {
  540. c, err := sw.transport.Accept(context.Background())
  541. if err != nil {
  542. switch err := err.(type) {
  543. case ErrRejected:
  544. if err.IsSelf() {
  545. // Remove the given address from the address book and add to our addresses
  546. // to avoid dialing in the future.
  547. addr := err.Addr()
  548. sw.addrBook.RemoveAddress(&addr)
  549. sw.addrBook.AddOurAddress(&addr)
  550. }
  551. sw.Logger.Info(
  552. "Inbound Peer rejected",
  553. "err", err,
  554. "numPeers", sw.peers.Size(),
  555. )
  556. continue
  557. case ErrFilterTimeout:
  558. sw.Logger.Error(
  559. "Peer filter timed out",
  560. "err", err,
  561. )
  562. continue
  563. case ErrTransportClosed:
  564. sw.Logger.Error(
  565. "Stopped accept routine, as transport is closed",
  566. "numPeers", sw.peers.Size(),
  567. )
  568. default:
  569. sw.Logger.Error(
  570. "Accept on transport errored",
  571. "err", err,
  572. "numPeers", sw.peers.Size(),
  573. )
  574. // We could instead have a retry loop around the acceptRoutine,
  575. // but that would need to stop and let the node shutdown eventually.
  576. // So might as well panic and let process managers restart the node.
  577. // There's no point in letting the node run without the acceptRoutine,
  578. // since it won't be able to accept new connections.
  579. panic(fmt.Errorf("accept routine exited: %v", err))
  580. }
  581. break
  582. }
  583. peerNodeInfo := c.NodeInfo()
  584. isPersistent := false
  585. addr, err := peerNodeInfo.NetAddress()
  586. if err == nil {
  587. isPersistent = sw.IsPeerPersistent(addr)
  588. }
  589. p := newPeer(
  590. newPeerConn(false, isPersistent, c),
  591. sw.reactorsByCh,
  592. sw.StopPeerForError,
  593. PeerMetrics(sw.metrics),
  594. )
  595. if !sw.IsPeerUnconditional(p.NodeInfo().ID()) {
  596. // Ignore connection if we already have enough peers.
  597. _, in, _ := sw.NumPeers()
  598. if in >= sw.config.MaxNumInboundPeers {
  599. sw.Logger.Info(
  600. "Ignoring inbound connection: already have enough inbound peers",
  601. "address", p.SocketAddr(),
  602. "have", in,
  603. "max", sw.config.MaxNumInboundPeers,
  604. )
  605. _ = p.CloseConn()
  606. continue
  607. }
  608. }
  609. if err := sw.addPeer(p); err != nil {
  610. _ = p.CloseConn()
  611. if p.IsRunning() {
  612. _ = p.Stop()
  613. }
  614. sw.Logger.Info(
  615. "Ignoring inbound connection: error while adding peer",
  616. "err", err,
  617. "id", p.ID(),
  618. )
  619. }
  620. }
  621. }
  622. // dial the peer; make secret connection; authenticate against the dialed ID;
  623. // add the peer.
  624. // if dialing fails, start the reconnect loop. If handshake fails, it's over.
  625. // If peer is started successfully, reconnectLoop will start when
  626. // StopPeerForError is called.
  627. func (sw *Switch) addOutboundPeerWithConfig(
  628. addr *NetAddress,
  629. cfg *config.P2PConfig,
  630. ) error {
  631. sw.Logger.Info("Dialing peer", "address", addr)
  632. // XXX(xla): Remove the leakage of test concerns in implementation.
  633. if cfg.TestDialFail {
  634. go sw.reconnectToPeer(addr)
  635. return fmt.Errorf("dial err (peerConfig.DialFail == true)")
  636. }
  637. c, err := sw.transport.Dial(context.Background(), Endpoint{
  638. Protocol: MConnProtocol,
  639. PeerID: addr.ID,
  640. IP: addr.IP,
  641. Port: addr.Port,
  642. })
  643. if err != nil {
  644. if e, ok := err.(ErrRejected); ok {
  645. if e.IsSelf() {
  646. // Remove the given address from the address book and add to our addresses
  647. // to avoid dialing in the future.
  648. sw.addrBook.RemoveAddress(addr)
  649. sw.addrBook.AddOurAddress(addr)
  650. return err
  651. }
  652. }
  653. // retry persistent peers after
  654. // any dial error besides IsSelf()
  655. if sw.IsPeerPersistent(addr) {
  656. go sw.reconnectToPeer(addr)
  657. }
  658. return err
  659. }
  660. p := newPeer(
  661. newPeerConn(true, sw.IsPeerPersistent(c.RemoteEndpoint().NetAddress()), c),
  662. sw.reactorsByCh,
  663. sw.StopPeerForError,
  664. PeerMetrics(sw.metrics),
  665. )
  666. if err := sw.addPeer(p); err != nil {
  667. _ = p.CloseConn()
  668. if p.IsRunning() {
  669. _ = p.Stop()
  670. }
  671. return err
  672. }
  673. return nil
  674. }
  675. func (sw *Switch) filterPeer(p Peer) error {
  676. // Avoid duplicate
  677. if sw.peers.Has(p.ID()) {
  678. return ErrRejected{id: p.ID(), isDuplicate: true}
  679. }
  680. errc := make(chan error, len(sw.peerFilters))
  681. for _, f := range sw.peerFilters {
  682. go func(f PeerFilterFunc, p Peer, errc chan<- error) {
  683. errc <- f(sw.peers, p)
  684. }(f, p, errc)
  685. }
  686. for i := 0; i < cap(errc); i++ {
  687. select {
  688. case err := <-errc:
  689. if err != nil {
  690. return ErrRejected{id: p.ID(), err: err, isFiltered: true}
  691. }
  692. case <-time.After(sw.filterTimeout):
  693. return ErrFilterTimeout{}
  694. }
  695. }
  696. return nil
  697. }
  698. // addPeer starts up the Peer and adds it to the Switch. Error is returned if
  699. // the peer is filtered out or failed to start or can't be added.
  700. func (sw *Switch) addPeer(p Peer) error {
  701. if err := sw.filterPeer(p); err != nil {
  702. return err
  703. }
  704. p.SetLogger(sw.Logger.With("peer", p.SocketAddr()))
  705. // Handle the shut down case where the switch has stopped but we're
  706. // concurrently trying to add a peer.
  707. if !sw.IsRunning() {
  708. // XXX should this return an error or just log and terminate?
  709. sw.Logger.Error("Won't start a peer - switch is not running", "peer", p)
  710. return nil
  711. }
  712. // Add some data to the peer, which is required by reactors.
  713. for _, reactor := range sw.reactors {
  714. p = reactor.InitPeer(p)
  715. }
  716. // Start the peer's send/recv routines.
  717. // Must start it before adding it to the peer set
  718. // to prevent Start and Stop from being called concurrently.
  719. err := p.Start()
  720. if err != nil {
  721. // Should never happen
  722. sw.Logger.Error("Error starting peer", "err", err, "peer", p)
  723. return err
  724. }
  725. // Add the peer to PeerSet. Do this before starting the reactors
  726. // so that if Receive errors, we will find the peer and remove it.
  727. // Add should not err since we already checked peers.Has().
  728. if err := sw.peers.Add(p); err != nil {
  729. return err
  730. }
  731. sw.metrics.Peers.Add(float64(1))
  732. // Start all the reactor protocols on the peer.
  733. for _, reactor := range sw.reactors {
  734. reactor.AddPeer(p)
  735. }
  736. sw.Logger.Info("Added peer", "peer", p)
  737. return nil
  738. }