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.

2061 lines
59 KiB

blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
privval: refactor Remote signers (#3370) This PR is related to #3107 and a continuation of #3351 It is important to emphasise that in the privval original design, client/server and listening/dialing roles are inverted and do not follow a conventional interaction. Given two hosts A and B: Host A is listener/client Host B is dialer/server (contains the secret key) When A requires a signature, it needs to wait for B to dial in before it can issue a request. A only accepts a single connection and any failure leads to dropping the connection and waiting for B to reconnect. The original rationale behind this design was based on security. Host B only allows outbound connections to a list of whitelisted hosts. It is not possible to reach B unless B dials in. There are no listening/open ports in B. This PR results in the following changes: Refactors ping/heartbeat to avoid previously existing race conditions. Separates transport (dialer/listener) from signing (client/server) concerns to simplify workflow. Unifies and abstracts away the differences between unix and tcp sockets. A single signer endpoint implementation unifies connection handling code (read/write/close/connection obj) The signer request handler (server side) is customizable to increase testability. Updates and extends unit tests A high level overview of the classes is as follows: Transport (endpoints): The following classes take care of establishing a connection SignerDialerEndpoint SignerListeningEndpoint SignerEndpoint groups common functionality (read/write/timeouts/etc.) Signing (client/server): The following classes take care of exchanging request/responses SignerClient SignerServer This PR also closes #3601 Commits: * refactoring - work in progress * reworking unit tests * Encapsulating and fixing unit tests * Improve tests * Clean up * Fix/improve unit tests * clean up tests * Improving service endpoint * fixing unit test * fix linter issues * avoid invalid cache values (improve later?) * complete implementation * wip * improved connection loop * Improve reconnections + fixing unit tests * addressing comments * small formatting changes * clean up * Update node/node.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * check during initialization * dropping connecting when writing fails * removing break * use t.log instead * unifying and using cmn.GetFreePort() * review fixes * reordering and unifying drop connection * closing instead of signalling * refactored service loop * removed superfluous brackets * GetPubKey can return errors * Revert "GetPubKey can return errors" This reverts commit 68c06f19b4650389d7e5ab1659b318889028202c. * adding entry to changelog * Update CHANGELOG_PENDING.md Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * updating node.go * review fixes * fixes linter * fixing unit test * small fixes in comments * addressing review comments * addressing review comments 2 * reverting suggestion * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * do not expose brokenSignerDialerEndpoint * clean up logging * unifying methods shorten test time signer also drops * reenabling pings * improving testability + unit test * fixing go fmt + unit test * remove unused code * Addressing review comments * simplifying connection workflow * fix linter/go import issue * using base service quit * updating comment * Simplifying design + adjusting names * fixing linter issues * refactoring test harness + fixes * Addressing review comments * cleaning up * adding additional error check
5 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 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
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
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
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
privval: refactor Remote signers (#3370) This PR is related to #3107 and a continuation of #3351 It is important to emphasise that in the privval original design, client/server and listening/dialing roles are inverted and do not follow a conventional interaction. Given two hosts A and B: Host A is listener/client Host B is dialer/server (contains the secret key) When A requires a signature, it needs to wait for B to dial in before it can issue a request. A only accepts a single connection and any failure leads to dropping the connection and waiting for B to reconnect. The original rationale behind this design was based on security. Host B only allows outbound connections to a list of whitelisted hosts. It is not possible to reach B unless B dials in. There are no listening/open ports in B. This PR results in the following changes: Refactors ping/heartbeat to avoid previously existing race conditions. Separates transport (dialer/listener) from signing (client/server) concerns to simplify workflow. Unifies and abstracts away the differences between unix and tcp sockets. A single signer endpoint implementation unifies connection handling code (read/write/close/connection obj) The signer request handler (server side) is customizable to increase testability. Updates and extends unit tests A high level overview of the classes is as follows: Transport (endpoints): The following classes take care of establishing a connection SignerDialerEndpoint SignerListeningEndpoint SignerEndpoint groups common functionality (read/write/timeouts/etc.) Signing (client/server): The following classes take care of exchanging request/responses SignerClient SignerServer This PR also closes #3601 Commits: * refactoring - work in progress * reworking unit tests * Encapsulating and fixing unit tests * Improve tests * Clean up * Fix/improve unit tests * clean up tests * Improving service endpoint * fixing unit test * fix linter issues * avoid invalid cache values (improve later?) * complete implementation * wip * improved connection loop * Improve reconnections + fixing unit tests * addressing comments * small formatting changes * clean up * Update node/node.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * check during initialization * dropping connecting when writing fails * removing break * use t.log instead * unifying and using cmn.GetFreePort() * review fixes * reordering and unifying drop connection * closing instead of signalling * refactored service loop * removed superfluous brackets * GetPubKey can return errors * Revert "GetPubKey can return errors" This reverts commit 68c06f19b4650389d7e5ab1659b318889028202c. * adding entry to changelog * Update CHANGELOG_PENDING.md Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * updating node.go * review fixes * fixes linter * fixing unit test * small fixes in comments * addressing review comments * addressing review comments 2 * reverting suggestion * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * do not expose brokenSignerDialerEndpoint * clean up logging * unifying methods shorten test time signer also drops * reenabling pings * improving testability + unit test * fixing go fmt + unit test * remove unused code * Addressing review comments * simplifying connection workflow * fix linter/go import issue * using base service quit * updating comment * Simplifying design + adjusting names * fixing linter issues * refactoring test harness + fixes * Addressing review comments * cleaning up * adding additional error check
5 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
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
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
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
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
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
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
limit number of /subscribe clients and queries per client (#3269) * limit number of /subscribe clients and queries per client Add the following config variables (under [rpc] section): * max_subscription_clients * max_subscriptions_per_client * timeout_broadcast_tx_commit Fixes #2826 new HTTPClient interface for subscriptions finalize HTTPClient events interface remove EventSubscriber fix data race ``` WARNING: DATA RACE Read at 0x00c000a36060 by goroutine 129: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe.func1() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:168 +0x1f0 Previous write at 0x00c000a36060 by goroutine 132: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:191 +0x4e0 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 129 (running) created at: github.com/tendermint/tendermint/rpc/client.(*Local).Subscribe() /go/src/github.com/tendermint/tendermint/rpc/client/localclient.go:164 +0x4b7 github.com/tendermint/tendermint/rpc/client.WaitForOneEvent() /go/src/github.com/tendermint/tendermint/rpc/client/helpers.go:64 +0x178 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync.func1() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:139 +0x298 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Goroutine 132 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 github.com/tendermint/tendermint/rpc/client_test.TestTxEventsSentWithBroadcastTxSync() /go/src/github.com/tendermint/tendermint/rpc/client/event_test.go:119 +0x186 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ================== ``` lite client works (tested manually) godoc comments httpclient: do not close the out channel use TimeoutBroadcastTxCommit no timeout for unsubscribe but 1s Local (5s HTTP) timeout for resubscribe format code change Subscribe#out cap to 1 and replace config vars with RPCConfig TimeoutBroadcastTxCommit can't be greater than rpcserver.WriteTimeout rpc: Context as first parameter to all functions reformat code fixes after my own review fixes after Ethan's review add test stubs fix config.toml * fixes after manual testing - rpc: do not recommend to use BroadcastTxCommit because it's slow and wastes Tendermint resources (pubsub) - rpc: better error in Subscribe and BroadcastTxCommit - HTTPClient: do not resubscribe if err = ErrAlreadySubscribed * fixes after Ismail's review * Update rpc/grpc/grpc_test.go Co-Authored-By: melekes <anton.kalyaev@gmail.com>
6 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
blockchain: Reorg reactor (#3561) * go routines in blockchain reactor * Added reference to the go routine diagram * Initial commit * cleanup * Undo testing_logger change, committed by mistake * Fix the test loggers * pulled some fsm code into pool.go * added pool tests * changes to the design added block requests under peer moved the request trigger in the reactor poolRoutine, triggered now by a ticker in general moved everything required for making block requests smarter in the poolRoutine added a simple map of heights to keep track of what will need to be requested next added a few more tests * send errors to FSM in a different channel than blocks send errors (RemovePeer) from switch on a different channel than the one receiving blocks renamed channels added more pool tests * more pool tests * lint errors * more tests * more tests * switch fast sync to new implementation * fixed data race in tests * cleanup * finished fsm tests * address golangci comments :) * address golangci comments :) * Added timeout on next block needed to advance * updating docs and cleanup * fix issue in test from previous cleanup * cleanup * Added termination scenarios, tests and more cleanup * small fixes to adr, comments and cleanup * Fix bug in sendRequest() If we tried to send a request to a peer not present in the switch, a missing continue statement caused the request to be blackholed in a peer that was removed and never retried. While this bug was manifesting, the reactor kept asking for other blocks that would be stored and never consumed. Added the number of unconsumed blocks in the math for requesting blocks ahead of current processing height so eventually there will be no more blocks requested until the already received ones are consumed. * remove bpPeer's didTimeout field * Use distinct err codes for peer timeout and FSM timeouts * Don't allow peers to update with lower height * review comments from Ethan and Zarko * some cleanup, renaming, comments * Move block execution in separate goroutine * Remove pool's numPending * review comments * fix lint, remove old blockchain reactor and duplicates in fsm tests * small reorg around peer after review comments * add the reactor spec * verify block only once * review comments * change to int for max number of pending requests * cleanup and godoc * Add configuration flag fast sync version * golangci fixes * fix config template * move both reactor versions under blockchain * cleanup, golint, renaming stuff * updated documentation, fixed more golint warnings * integrate with behavior package * sync with master * gofmt * add changelog_pending entry * move to improvments * suggestion to changelog entry
5 years ago
privval: refactor Remote signers (#3370) This PR is related to #3107 and a continuation of #3351 It is important to emphasise that in the privval original design, client/server and listening/dialing roles are inverted and do not follow a conventional interaction. Given two hosts A and B: Host A is listener/client Host B is dialer/server (contains the secret key) When A requires a signature, it needs to wait for B to dial in before it can issue a request. A only accepts a single connection and any failure leads to dropping the connection and waiting for B to reconnect. The original rationale behind this design was based on security. Host B only allows outbound connections to a list of whitelisted hosts. It is not possible to reach B unless B dials in. There are no listening/open ports in B. This PR results in the following changes: Refactors ping/heartbeat to avoid previously existing race conditions. Separates transport (dialer/listener) from signing (client/server) concerns to simplify workflow. Unifies and abstracts away the differences between unix and tcp sockets. A single signer endpoint implementation unifies connection handling code (read/write/close/connection obj) The signer request handler (server side) is customizable to increase testability. Updates and extends unit tests A high level overview of the classes is as follows: Transport (endpoints): The following classes take care of establishing a connection SignerDialerEndpoint SignerListeningEndpoint SignerEndpoint groups common functionality (read/write/timeouts/etc.) Signing (client/server): The following classes take care of exchanging request/responses SignerClient SignerServer This PR also closes #3601 Commits: * refactoring - work in progress * reworking unit tests * Encapsulating and fixing unit tests * Improve tests * Clean up * Fix/improve unit tests * clean up tests * Improving service endpoint * fixing unit test * fix linter issues * avoid invalid cache values (improve later?) * complete implementation * wip * improved connection loop * Improve reconnections + fixing unit tests * addressing comments * small formatting changes * clean up * Update node/node.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * check during initialization * dropping connecting when writing fails * removing break * use t.log instead * unifying and using cmn.GetFreePort() * review fixes * reordering and unifying drop connection * closing instead of signalling * refactored service loop * removed superfluous brackets * GetPubKey can return errors * Revert "GetPubKey can return errors" This reverts commit 68c06f19b4650389d7e5ab1659b318889028202c. * adding entry to changelog * Update CHANGELOG_PENDING.md Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * updating node.go * review fixes * fixes linter * fixing unit test * small fixes in comments * addressing review comments * addressing review comments 2 * reverting suggestion * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * do not expose brokenSignerDialerEndpoint * clean up logging * unifying methods shorten test time signer also drops * reenabling pings * improving testability + unit test * fixing go fmt + unit test * remove unused code * Addressing review comments * simplifying connection workflow * fix linter/go import issue * using base service quit * updating comment * Simplifying design + adjusting names * fixing linter issues * refactoring test harness + fixes * Addressing review comments * cleaning up * adding additional error check
5 years ago
Close and retry a RemoteSigner on err (#2923) * Close and recreate a RemoteSigner on err * Update changelog * Address Anton's comments / suggestions: - update changelog - restart TCPVal - shut down on `ErrUnexpectedResponse` * re-init remote signer client with fresh connection if Ping fails - add/update TODOs in secret connection - rename tcp.go -> tcp_client.go, same with ipc to clarify their purpose * account for `conn returned by waitConnection can be `nil` - also add TODO about RemoteSigner conn field * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn - add rwmutex for conn field in IPC * comments and doc.go * fix ipc tests. fixes #2677 * use constants for tests * cleanup some error statements * fixes #2784, race in tests * remove print statement * minor fixes from review * update comment on sts spec * cosmetics * p2p/conn: add failing tests * p2p/conn: make SecretConnection thread safe * changelog * IPCVal signer refactor - use a .reset() method - don't use embedded RemoteSignerClient - guard RemoteSignerClient with mutex - drop the .conn - expose Close() on RemoteSignerClient * apply IPCVal refactor to TCPVal * remove mtx from RemoteSignerClient * consolidate IPCVal and TCPVal, fixes #3104 - done in tcp_client.go - now called SocketVal - takes a listener in the constructor - make tcpListener and unixListener contain all the differences * delete ipc files * introduce unix and tcp dialer for RemoteSigner * rename files - drop tcp_ prefix - rename priv_validator.go to file.go * bring back listener options * fix node * fix priv_val_server * fix node test * minor cleanup and comments
6 years ago
privval: refactor Remote signers (#3370) This PR is related to #3107 and a continuation of #3351 It is important to emphasise that in the privval original design, client/server and listening/dialing roles are inverted and do not follow a conventional interaction. Given two hosts A and B: Host A is listener/client Host B is dialer/server (contains the secret key) When A requires a signature, it needs to wait for B to dial in before it can issue a request. A only accepts a single connection and any failure leads to dropping the connection and waiting for B to reconnect. The original rationale behind this design was based on security. Host B only allows outbound connections to a list of whitelisted hosts. It is not possible to reach B unless B dials in. There are no listening/open ports in B. This PR results in the following changes: Refactors ping/heartbeat to avoid previously existing race conditions. Separates transport (dialer/listener) from signing (client/server) concerns to simplify workflow. Unifies and abstracts away the differences between unix and tcp sockets. A single signer endpoint implementation unifies connection handling code (read/write/close/connection obj) The signer request handler (server side) is customizable to increase testability. Updates and extends unit tests A high level overview of the classes is as follows: Transport (endpoints): The following classes take care of establishing a connection SignerDialerEndpoint SignerListeningEndpoint SignerEndpoint groups common functionality (read/write/timeouts/etc.) Signing (client/server): The following classes take care of exchanging request/responses SignerClient SignerServer This PR also closes #3601 Commits: * refactoring - work in progress * reworking unit tests * Encapsulating and fixing unit tests * Improve tests * Clean up * Fix/improve unit tests * clean up tests * Improving service endpoint * fixing unit test * fix linter issues * avoid invalid cache values (improve later?) * complete implementation * wip * improved connection loop * Improve reconnections + fixing unit tests * addressing comments * small formatting changes * clean up * Update node/node.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * check during initialization * dropping connecting when writing fails * removing break * use t.log instead * unifying and using cmn.GetFreePort() * review fixes * reordering and unifying drop connection * closing instead of signalling * refactored service loop * removed superfluous brackets * GetPubKey can return errors * Revert "GetPubKey can return errors" This reverts commit 68c06f19b4650389d7e5ab1659b318889028202c. * adding entry to changelog * Update CHANGELOG_PENDING.md Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * updating node.go * review fixes * fixes linter * fixing unit test * small fixes in comments * addressing review comments * addressing review comments 2 * reverting suggestion * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * do not expose brokenSignerDialerEndpoint * clean up logging * unifying methods shorten test time signer also drops * reenabling pings * improving testability + unit test * fixing go fmt + unit test * remove unused code * Addressing review comments * simplifying connection workflow * fix linter/go import issue * using base service quit * updating comment * Simplifying design + adjusting names * fixing linter issues * refactoring test harness + fixes * Addressing review comments * cleaning up * adding additional error check
5 years ago
  1. package node
  2. import (
  3. "bytes"
  4. "context"
  5. "errors"
  6. "fmt"
  7. "math"
  8. "net"
  9. "net/http"
  10. _ "net/http/pprof" // nolint: gosec // securely exposed on separate, optional port
  11. "strconv"
  12. "time"
  13. "github.com/prometheus/client_golang/prometheus"
  14. "github.com/prometheus/client_golang/prometheus/promhttp"
  15. "github.com/rs/cors"
  16. dbm "github.com/tendermint/tm-db"
  17. abci "github.com/tendermint/tendermint/abci/types"
  18. bcv0 "github.com/tendermint/tendermint/blockchain/v0"
  19. bcv2 "github.com/tendermint/tendermint/blockchain/v2"
  20. cfg "github.com/tendermint/tendermint/config"
  21. cs "github.com/tendermint/tendermint/consensus"
  22. "github.com/tendermint/tendermint/crypto"
  23. "github.com/tendermint/tendermint/evidence"
  24. tmjson "github.com/tendermint/tendermint/libs/json"
  25. "github.com/tendermint/tendermint/libs/log"
  26. tmnet "github.com/tendermint/tendermint/libs/net"
  27. tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
  28. "github.com/tendermint/tendermint/libs/service"
  29. "github.com/tendermint/tendermint/light"
  30. mempl "github.com/tendermint/tendermint/mempool"
  31. "github.com/tendermint/tendermint/p2p"
  32. "github.com/tendermint/tendermint/p2p/pex"
  33. "github.com/tendermint/tendermint/privval"
  34. tmgrpc "github.com/tendermint/tendermint/privval/grpc"
  35. protop2p "github.com/tendermint/tendermint/proto/tendermint/p2p"
  36. "github.com/tendermint/tendermint/proxy"
  37. rpccore "github.com/tendermint/tendermint/rpc/core"
  38. grpccore "github.com/tendermint/tendermint/rpc/grpc"
  39. rpcserver "github.com/tendermint/tendermint/rpc/jsonrpc/server"
  40. sm "github.com/tendermint/tendermint/state"
  41. "github.com/tendermint/tendermint/state/indexer"
  42. blockidxkv "github.com/tendermint/tendermint/state/indexer/block/kv"
  43. blockidxnull "github.com/tendermint/tendermint/state/indexer/block/null"
  44. "github.com/tendermint/tendermint/state/indexer/tx/kv"
  45. "github.com/tendermint/tendermint/state/indexer/tx/null"
  46. "github.com/tendermint/tendermint/statesync"
  47. "github.com/tendermint/tendermint/store"
  48. "github.com/tendermint/tendermint/types"
  49. tmtime "github.com/tendermint/tendermint/types/time"
  50. "github.com/tendermint/tendermint/version"
  51. )
  52. // DBContext specifies config information for loading a new DB.
  53. type DBContext struct {
  54. ID string
  55. Config *cfg.Config
  56. }
  57. // DBProvider takes a DBContext and returns an instantiated DB.
  58. type DBProvider func(*DBContext) (dbm.DB, error)
  59. // DefaultDBProvider returns a database using the DBBackend and DBDir
  60. // specified in the ctx.Config.
  61. func DefaultDBProvider(ctx *DBContext) (dbm.DB, error) {
  62. dbType := dbm.BackendType(ctx.Config.DBBackend)
  63. return dbm.NewDB(ctx.ID, dbType, ctx.Config.DBDir())
  64. }
  65. // GenesisDocProvider returns a GenesisDoc.
  66. // It allows the GenesisDoc to be pulled from sources other than the
  67. // filesystem, for instance from a distributed key-value store cluster.
  68. type GenesisDocProvider func() (*types.GenesisDoc, error)
  69. // DefaultGenesisDocProviderFunc returns a GenesisDocProvider that loads
  70. // the GenesisDoc from the config.GenesisFile() on the filesystem.
  71. func DefaultGenesisDocProviderFunc(config *cfg.Config) GenesisDocProvider {
  72. return func() (*types.GenesisDoc, error) {
  73. return types.GenesisDocFromFile(config.GenesisFile())
  74. }
  75. }
  76. // Provider takes a config and a logger and returns a ready to go Node.
  77. type Provider func(*cfg.Config, log.Logger) (*Node, error)
  78. // DefaultNewNode returns a Tendermint node with default settings for the
  79. // PrivValidator, ClientCreator, GenesisDoc, and DBProvider.
  80. // It implements NodeProvider.
  81. func DefaultNewNode(config *cfg.Config, logger log.Logger) (*Node, error) {
  82. nodeKey, err := p2p.LoadOrGenNodeKey(config.NodeKeyFile())
  83. if err != nil {
  84. return nil, fmt.Errorf("failed to load or gen node key %s: %w", config.NodeKeyFile(), err)
  85. }
  86. if config.Mode == cfg.ModeSeed {
  87. return NewSeedNode(config,
  88. DefaultDBProvider,
  89. nodeKey,
  90. DefaultGenesisDocProviderFunc(config),
  91. logger,
  92. )
  93. }
  94. var pval *privval.FilePV
  95. if config.Mode == cfg.ModeValidator {
  96. pval, err = privval.LoadOrGenFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile())
  97. if err != nil {
  98. return nil, err
  99. }
  100. } else {
  101. pval = nil
  102. }
  103. appClient, _ := proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir())
  104. return NewNode(config,
  105. pval,
  106. nodeKey,
  107. appClient,
  108. DefaultGenesisDocProviderFunc(config),
  109. DefaultDBProvider,
  110. DefaultMetricsProvider(config.Instrumentation),
  111. logger,
  112. )
  113. }
  114. // MetricsProvider returns a consensus, p2p and mempool Metrics.
  115. type MetricsProvider func(chainID string) (*cs.Metrics, *p2p.Metrics, *mempl.Metrics, *sm.Metrics)
  116. // DefaultMetricsProvider returns Metrics build using Prometheus client library
  117. // if Prometheus is enabled. Otherwise, it returns no-op Metrics.
  118. func DefaultMetricsProvider(config *cfg.InstrumentationConfig) MetricsProvider {
  119. return func(chainID string) (*cs.Metrics, *p2p.Metrics, *mempl.Metrics, *sm.Metrics) {
  120. if config.Prometheus {
  121. return cs.PrometheusMetrics(config.Namespace, "chain_id", chainID),
  122. p2p.PrometheusMetrics(config.Namespace, "chain_id", chainID),
  123. mempl.PrometheusMetrics(config.Namespace, "chain_id", chainID),
  124. sm.PrometheusMetrics(config.Namespace, "chain_id", chainID)
  125. }
  126. return cs.NopMetrics(), p2p.NopMetrics(), mempl.NopMetrics(), sm.NopMetrics()
  127. }
  128. }
  129. // Option sets a parameter for the node.
  130. type Option func(*Node)
  131. // Temporary interface for switching to fast sync, we should get rid of v0.
  132. // See: https://github.com/tendermint/tendermint/issues/4595
  133. type fastSyncReactor interface {
  134. SwitchToFastSync(sm.State) error
  135. }
  136. // CustomReactors allows you to add custom reactors (name -> p2p.Reactor) to
  137. // the node's Switch.
  138. //
  139. // WARNING: using any name from the below list of the existing reactors will
  140. // result in replacing it with the custom one.
  141. //
  142. // - MEMPOOL
  143. // - BLOCKCHAIN
  144. // - CONSENSUS
  145. // - EVIDENCE
  146. // - PEX
  147. // - STATESYNC
  148. func CustomReactors(reactors map[string]p2p.Reactor) Option {
  149. return func(n *Node) {
  150. for name, reactor := range reactors {
  151. if existingReactor := n.sw.Reactor(name); existingReactor != nil {
  152. n.sw.Logger.Info("Replacing existing reactor with a custom one",
  153. "name", name, "existing", existingReactor, "custom", reactor)
  154. n.sw.RemoveReactor(name, existingReactor)
  155. }
  156. n.sw.AddReactor(name, reactor)
  157. }
  158. }
  159. }
  160. // StateProvider overrides the state provider used by state sync to retrieve trusted app hashes and
  161. // build a State object for bootstrapping the node.
  162. // WARNING: this interface is considered unstable and subject to change.
  163. func StateProvider(stateProvider statesync.StateProvider) Option {
  164. return func(n *Node) {
  165. n.stateSyncProvider = stateProvider
  166. }
  167. }
  168. //------------------------------------------------------------------------------
  169. // Node is the highest level interface to a full Tendermint node.
  170. // It includes all configuration information and running services.
  171. type Node struct {
  172. service.BaseService
  173. // config
  174. config *cfg.Config
  175. genesisDoc *types.GenesisDoc // initial validator set
  176. privValidator types.PrivValidator // local node's validator key
  177. // network
  178. transport *p2p.MConnTransport
  179. sw *p2p.Switch // p2p connections
  180. peerManager *p2p.PeerManager
  181. router *p2p.Router
  182. addrBook pex.AddrBook // known peers
  183. nodeInfo p2p.NodeInfo
  184. nodeKey p2p.NodeKey // our node privkey
  185. isListening bool
  186. // services
  187. eventBus *types.EventBus // pub/sub for services
  188. stateStore sm.Store
  189. blockStore *store.BlockStore // store the blockchain to disk
  190. bcReactor service.Service // for fast-syncing
  191. mempoolReactor *mempl.Reactor // for gossipping transactions
  192. mempool mempl.Mempool
  193. stateSync bool // whether the node should state sync on startup
  194. stateSyncReactor *statesync.Reactor // for hosting and restoring state sync snapshots
  195. stateSyncProvider statesync.StateProvider // provides state data for bootstrapping a node
  196. stateSyncGenesis sm.State // provides the genesis state for state sync
  197. consensusState *cs.State // latest consensus state
  198. consensusReactor *cs.Reactor // for participating in the consensus
  199. pexReactor *pex.Reactor // for exchanging peer addresses
  200. pexReactorV2 *pex.ReactorV2 // for exchanging peer addresses
  201. evidenceReactor *evidence.Reactor
  202. evidencePool *evidence.Pool // tracking evidence
  203. proxyApp proxy.AppConns // connection to the application
  204. rpcListeners []net.Listener // rpc servers
  205. txIndexer indexer.TxIndexer
  206. blockIndexer indexer.BlockIndexer
  207. indexerService *indexer.Service
  208. prometheusSrv *http.Server
  209. }
  210. func initDBs(config *cfg.Config, dbProvider DBProvider) (blockStore *store.BlockStore, stateDB dbm.DB, err error) {
  211. var blockStoreDB dbm.DB
  212. blockStoreDB, err = dbProvider(&DBContext{"blockstore", config})
  213. if err != nil {
  214. return
  215. }
  216. blockStore = store.NewBlockStore(blockStoreDB)
  217. stateDB, err = dbProvider(&DBContext{"state", config})
  218. return
  219. }
  220. func createAndStartProxyAppConns(clientCreator proxy.ClientCreator, logger log.Logger) (proxy.AppConns, error) {
  221. proxyApp := proxy.NewAppConns(clientCreator)
  222. proxyApp.SetLogger(logger.With("module", "proxy"))
  223. if err := proxyApp.Start(); err != nil {
  224. return nil, fmt.Errorf("error starting proxy app connections: %v", err)
  225. }
  226. return proxyApp, nil
  227. }
  228. func createAndStartEventBus(logger log.Logger) (*types.EventBus, error) {
  229. eventBus := types.NewEventBus()
  230. eventBus.SetLogger(logger.With("module", "events"))
  231. if err := eventBus.Start(); err != nil {
  232. return nil, err
  233. }
  234. return eventBus, nil
  235. }
  236. func createAndStartIndexerService(
  237. config *cfg.Config,
  238. dbProvider DBProvider,
  239. eventBus *types.EventBus,
  240. logger log.Logger,
  241. ) (*indexer.Service, indexer.TxIndexer, indexer.BlockIndexer, error) {
  242. var (
  243. txIndexer indexer.TxIndexer
  244. blockIndexer indexer.BlockIndexer
  245. )
  246. switch config.TxIndex.Indexer {
  247. case "kv":
  248. store, err := dbProvider(&DBContext{"tx_index", config})
  249. if err != nil {
  250. return nil, nil, nil, err
  251. }
  252. txIndexer = kv.NewTxIndex(store)
  253. blockIndexer = blockidxkv.New(dbm.NewPrefixDB(store, []byte("block_events")))
  254. default:
  255. txIndexer = &null.TxIndex{}
  256. blockIndexer = &blockidxnull.BlockerIndexer{}
  257. }
  258. indexerService := indexer.NewIndexerService(txIndexer, blockIndexer, eventBus)
  259. indexerService.SetLogger(logger.With("module", "txindex"))
  260. if err := indexerService.Start(); err != nil {
  261. return nil, nil, nil, err
  262. }
  263. return indexerService, txIndexer, blockIndexer, nil
  264. }
  265. func doHandshake(
  266. stateStore sm.Store,
  267. state sm.State,
  268. blockStore sm.BlockStore,
  269. genDoc *types.GenesisDoc,
  270. eventBus types.BlockEventPublisher,
  271. proxyApp proxy.AppConns,
  272. consensusLogger log.Logger) error {
  273. handshaker := cs.NewHandshaker(stateStore, state, blockStore, genDoc)
  274. handshaker.SetLogger(consensusLogger)
  275. handshaker.SetEventBus(eventBus)
  276. if err := handshaker.Handshake(proxyApp); err != nil {
  277. return fmt.Errorf("error during handshake: %v", err)
  278. }
  279. return nil
  280. }
  281. func logNodeStartupInfo(state sm.State, pubKey crypto.PubKey, logger, consensusLogger log.Logger, mode string) {
  282. // Log the version info.
  283. logger.Info("Version info",
  284. "software", version.TMCoreSemVer,
  285. "block", version.BlockProtocol,
  286. "p2p", version.P2PProtocol,
  287. "mode", mode,
  288. )
  289. // If the state and software differ in block version, at least log it.
  290. if state.Version.Consensus.Block != version.BlockProtocol {
  291. logger.Info("Software and state have different block protocols",
  292. "software", version.BlockProtocol,
  293. "state", state.Version.Consensus.Block,
  294. )
  295. }
  296. switch {
  297. case mode == cfg.ModeFull:
  298. consensusLogger.Info("This node is a fullnode")
  299. case mode == cfg.ModeValidator:
  300. addr := pubKey.Address()
  301. // Log whether this node is a validator or an observer
  302. if state.Validators.HasAddress(addr) {
  303. consensusLogger.Info("This node is a validator", "addr", addr, "pubKey", pubKey.Bytes())
  304. } else {
  305. consensusLogger.Info("This node is a validator (NOT in the active validator set)",
  306. "addr", addr, "pubKey", pubKey.Bytes())
  307. }
  308. }
  309. }
  310. func onlyValidatorIsUs(state sm.State, pubKey crypto.PubKey) bool {
  311. if state.Validators.Size() > 1 {
  312. return false
  313. }
  314. addr, _ := state.Validators.GetByIndex(0)
  315. return pubKey != nil && bytes.Equal(pubKey.Address(), addr)
  316. }
  317. func createMempoolReactor(
  318. config *cfg.Config,
  319. proxyApp proxy.AppConns,
  320. state sm.State,
  321. memplMetrics *mempl.Metrics,
  322. peerManager *p2p.PeerManager,
  323. router *p2p.Router,
  324. logger log.Logger,
  325. ) (*p2p.ReactorShim, *mempl.Reactor, *mempl.CListMempool) {
  326. logger = logger.With("module", "mempool")
  327. mempool := mempl.NewCListMempool(
  328. config.Mempool,
  329. proxyApp.Mempool(),
  330. state.LastBlockHeight,
  331. mempl.WithMetrics(memplMetrics),
  332. mempl.WithPreCheck(sm.TxPreCheck(state)),
  333. mempl.WithPostCheck(sm.TxPostCheck(state)),
  334. )
  335. mempool.SetLogger(logger)
  336. channelShims := mempl.GetChannelShims(config.Mempool)
  337. reactorShim := p2p.NewReactorShim(logger, "MempoolShim", channelShims)
  338. var (
  339. channels map[p2p.ChannelID]*p2p.Channel
  340. peerUpdates *p2p.PeerUpdates
  341. )
  342. if config.P2P.DisableLegacy {
  343. channels = makeChannelsFromShims(router, channelShims)
  344. peerUpdates = peerManager.Subscribe()
  345. } else {
  346. channels = getChannelsFromShim(reactorShim)
  347. peerUpdates = reactorShim.PeerUpdates
  348. }
  349. reactor := mempl.NewReactor(
  350. logger,
  351. config.Mempool,
  352. peerManager,
  353. mempool,
  354. channels[mempl.MempoolChannel],
  355. peerUpdates,
  356. )
  357. if config.Consensus.WaitForTxs() {
  358. mempool.EnableTxsAvailable()
  359. }
  360. return reactorShim, reactor, mempool
  361. }
  362. func createEvidenceReactor(
  363. config *cfg.Config,
  364. dbProvider DBProvider,
  365. stateDB dbm.DB,
  366. blockStore *store.BlockStore,
  367. peerManager *p2p.PeerManager,
  368. router *p2p.Router,
  369. logger log.Logger,
  370. ) (*p2p.ReactorShim, *evidence.Reactor, *evidence.Pool, error) {
  371. evidenceDB, err := dbProvider(&DBContext{"evidence", config})
  372. if err != nil {
  373. return nil, nil, nil, err
  374. }
  375. logger = logger.With("module", "evidence")
  376. reactorShim := p2p.NewReactorShim(logger, "EvidenceShim", evidence.ChannelShims)
  377. evidencePool, err := evidence.NewPool(logger, evidenceDB, sm.NewStore(stateDB), blockStore)
  378. if err != nil {
  379. return nil, nil, nil, err
  380. }
  381. var (
  382. channels map[p2p.ChannelID]*p2p.Channel
  383. peerUpdates *p2p.PeerUpdates
  384. )
  385. if config.P2P.DisableLegacy {
  386. channels = makeChannelsFromShims(router, evidence.ChannelShims)
  387. peerUpdates = peerManager.Subscribe()
  388. } else {
  389. channels = getChannelsFromShim(reactorShim)
  390. peerUpdates = reactorShim.PeerUpdates
  391. }
  392. evidenceReactor := evidence.NewReactor(
  393. logger,
  394. channels[evidence.EvidenceChannel],
  395. peerUpdates,
  396. evidencePool,
  397. )
  398. return reactorShim, evidenceReactor, evidencePool, nil
  399. }
  400. func createBlockchainReactor(
  401. logger log.Logger,
  402. config *cfg.Config,
  403. state sm.State,
  404. blockExec *sm.BlockExecutor,
  405. blockStore *store.BlockStore,
  406. csReactor *cs.Reactor,
  407. peerManager *p2p.PeerManager,
  408. router *p2p.Router,
  409. fastSync bool,
  410. ) (*p2p.ReactorShim, service.Service, error) {
  411. logger = logger.With("module", "blockchain")
  412. switch config.FastSync.Version {
  413. case cfg.BlockchainV0:
  414. reactorShim := p2p.NewReactorShim(logger, "BlockchainShim", bcv0.ChannelShims)
  415. var (
  416. channels map[p2p.ChannelID]*p2p.Channel
  417. peerUpdates *p2p.PeerUpdates
  418. )
  419. if config.P2P.DisableLegacy {
  420. channels = makeChannelsFromShims(router, bcv0.ChannelShims)
  421. peerUpdates = peerManager.Subscribe()
  422. } else {
  423. channels = getChannelsFromShim(reactorShim)
  424. peerUpdates = reactorShim.PeerUpdates
  425. }
  426. reactor, err := bcv0.NewReactor(
  427. logger, state.Copy(), blockExec, blockStore, csReactor,
  428. channels[bcv0.BlockchainChannel], peerUpdates, fastSync,
  429. )
  430. if err != nil {
  431. return nil, nil, err
  432. }
  433. return reactorShim, reactor, nil
  434. case cfg.BlockchainV2:
  435. reactor := bcv2.NewBlockchainReactor(state.Copy(), blockExec, blockStore, fastSync)
  436. reactor.SetLogger(logger)
  437. return nil, reactor, nil
  438. default:
  439. return nil, nil, fmt.Errorf("unknown fastsync version %s", config.FastSync.Version)
  440. }
  441. }
  442. func createConsensusReactor(
  443. config *cfg.Config,
  444. state sm.State,
  445. blockExec *sm.BlockExecutor,
  446. blockStore sm.BlockStore,
  447. mempool *mempl.CListMempool,
  448. evidencePool *evidence.Pool,
  449. privValidator types.PrivValidator,
  450. csMetrics *cs.Metrics,
  451. waitSync bool,
  452. eventBus *types.EventBus,
  453. peerManager *p2p.PeerManager,
  454. router *p2p.Router,
  455. logger log.Logger,
  456. ) (*p2p.ReactorShim, *cs.Reactor, *cs.State) {
  457. consensusState := cs.NewState(
  458. config.Consensus,
  459. state.Copy(),
  460. blockExec,
  461. blockStore,
  462. mempool,
  463. evidencePool,
  464. cs.StateMetrics(csMetrics),
  465. )
  466. consensusState.SetLogger(logger)
  467. if privValidator != nil && config.Mode == cfg.ModeValidator {
  468. consensusState.SetPrivValidator(privValidator)
  469. }
  470. reactorShim := p2p.NewReactorShim(logger, "ConsensusShim", cs.ChannelShims)
  471. var (
  472. channels map[p2p.ChannelID]*p2p.Channel
  473. peerUpdates *p2p.PeerUpdates
  474. )
  475. if config.P2P.DisableLegacy {
  476. channels = makeChannelsFromShims(router, cs.ChannelShims)
  477. peerUpdates = peerManager.Subscribe()
  478. } else {
  479. channels = getChannelsFromShim(reactorShim)
  480. peerUpdates = reactorShim.PeerUpdates
  481. }
  482. reactor := cs.NewReactor(
  483. logger,
  484. consensusState,
  485. channels[cs.StateChannel],
  486. channels[cs.DataChannel],
  487. channels[cs.VoteChannel],
  488. channels[cs.VoteSetBitsChannel],
  489. peerUpdates,
  490. waitSync,
  491. cs.ReactorMetrics(csMetrics),
  492. )
  493. // Services which will be publishing and/or subscribing for messages (events)
  494. // consensusReactor will set it on consensusState and blockExecutor.
  495. reactor.SetEventBus(eventBus)
  496. return reactorShim, reactor, consensusState
  497. }
  498. func createTransport(logger log.Logger, config *cfg.Config) *p2p.MConnTransport {
  499. return p2p.NewMConnTransport(
  500. logger, p2p.MConnConfig(config.P2P), []*p2p.ChannelDescriptor{},
  501. p2p.MConnTransportOptions{
  502. MaxAcceptedConnections: uint32(config.P2P.MaxNumInboundPeers +
  503. len(splitAndTrimEmpty(config.P2P.UnconditionalPeerIDs, ",", " ")),
  504. ),
  505. },
  506. )
  507. }
  508. func createPeerManager(
  509. config *cfg.Config,
  510. dbProvider DBProvider,
  511. p2pLogger log.Logger,
  512. nodeID p2p.NodeID) (*p2p.PeerManager, error) {
  513. var maxConns uint16
  514. switch {
  515. case config.P2P.MaxConnections > 0:
  516. maxConns = config.P2P.MaxConnections
  517. case config.P2P.MaxNumInboundPeers > 0 && config.P2P.MaxNumOutboundPeers > 0:
  518. x := config.P2P.MaxNumInboundPeers + config.P2P.MaxNumOutboundPeers
  519. if x > math.MaxUint16 {
  520. return nil, fmt.Errorf(
  521. "max inbound peers (%d) + max outbound peers (%d) exceeds maximum (%d)",
  522. config.P2P.MaxNumInboundPeers,
  523. config.P2P.MaxNumOutboundPeers,
  524. math.MaxUint16,
  525. )
  526. }
  527. maxConns = uint16(x)
  528. default:
  529. maxConns = 64
  530. }
  531. options := p2p.PeerManagerOptions{
  532. MaxConnected: maxConns,
  533. MaxConnectedUpgrade: 4,
  534. MaxPeers: 1000,
  535. MinRetryTime: 100 * time.Millisecond,
  536. MaxRetryTime: 8 * time.Hour,
  537. MaxRetryTimePersistent: 5 * time.Minute,
  538. RetryTimeJitter: 3 * time.Second,
  539. }
  540. peers := []p2p.NodeAddress{}
  541. for _, p := range splitAndTrimEmpty(config.P2P.PersistentPeers, ",", " ") {
  542. address, err := p2p.ParseNodeAddress(p)
  543. if err != nil {
  544. return nil, fmt.Errorf("invalid peer address %q: %w", p, err)
  545. }
  546. peers = append(peers, address)
  547. options.PersistentPeers = append(options.PersistentPeers, address.NodeID)
  548. }
  549. for _, p := range splitAndTrimEmpty(config.P2P.BootstrapPeers, ",", " ") {
  550. address, err := p2p.ParseNodeAddress(p)
  551. if err != nil {
  552. return nil, fmt.Errorf("invalid peer address %q: %w", p, err)
  553. }
  554. peers = append(peers, address)
  555. }
  556. peerDB, err := dbProvider(&DBContext{"peerstore", config})
  557. if err != nil {
  558. return nil, err
  559. }
  560. peerManager, err := p2p.NewPeerManager(nodeID, peerDB, options)
  561. if err != nil {
  562. return nil, fmt.Errorf("failed to create peer manager: %w", err)
  563. }
  564. for _, peer := range peers {
  565. if err := peerManager.Add(peer); err != nil {
  566. return nil, fmt.Errorf("failed to add peer %q: %w", peer, err)
  567. }
  568. }
  569. return peerManager, nil
  570. }
  571. func createRouter(
  572. p2pLogger log.Logger,
  573. p2pMetrics *p2p.Metrics,
  574. nodeInfo p2p.NodeInfo,
  575. privKey crypto.PrivKey,
  576. peerManager *p2p.PeerManager,
  577. transport p2p.Transport,
  578. options p2p.RouterOptions,
  579. ) (*p2p.Router, error) {
  580. return p2p.NewRouter(
  581. p2pLogger,
  582. p2pMetrics,
  583. nodeInfo,
  584. privKey,
  585. peerManager,
  586. []p2p.Transport{transport},
  587. options,
  588. )
  589. }
  590. func createSwitch(
  591. config *cfg.Config,
  592. transport p2p.Transport,
  593. p2pMetrics *p2p.Metrics,
  594. mempoolReactor *p2p.ReactorShim,
  595. bcReactor p2p.Reactor,
  596. stateSyncReactor *p2p.ReactorShim,
  597. consensusReactor *p2p.ReactorShim,
  598. evidenceReactor *p2p.ReactorShim,
  599. proxyApp proxy.AppConns,
  600. nodeInfo p2p.NodeInfo,
  601. nodeKey p2p.NodeKey,
  602. p2pLogger log.Logger,
  603. ) *p2p.Switch {
  604. var (
  605. connFilters = []p2p.ConnFilterFunc{}
  606. peerFilters = []p2p.PeerFilterFunc{}
  607. )
  608. if !config.P2P.AllowDuplicateIP {
  609. connFilters = append(connFilters, p2p.ConnDuplicateIPFilter)
  610. }
  611. // Filter peers by addr or pubkey with an ABCI query.
  612. // If the query return code is OK, add peer.
  613. if config.FilterPeers {
  614. connFilters = append(
  615. connFilters,
  616. // ABCI query for address filtering.
  617. func(_ p2p.ConnSet, c net.Conn, _ []net.IP) error {
  618. res, err := proxyApp.Query().QuerySync(context.Background(), abci.RequestQuery{
  619. Path: fmt.Sprintf("/p2p/filter/addr/%s", c.RemoteAddr().String()),
  620. })
  621. if err != nil {
  622. return err
  623. }
  624. if res.IsErr() {
  625. return fmt.Errorf("error querying abci app: %v", res)
  626. }
  627. return nil
  628. },
  629. )
  630. peerFilters = append(
  631. peerFilters,
  632. // ABCI query for ID filtering.
  633. func(_ p2p.IPeerSet, p p2p.Peer) error {
  634. res, err := proxyApp.Query().QuerySync(context.Background(), abci.RequestQuery{
  635. Path: fmt.Sprintf("/p2p/filter/id/%s", p.ID()),
  636. })
  637. if err != nil {
  638. return err
  639. }
  640. if res.IsErr() {
  641. return fmt.Errorf("error querying abci app: %v", res)
  642. }
  643. return nil
  644. },
  645. )
  646. }
  647. sw := p2p.NewSwitch(
  648. config.P2P,
  649. transport,
  650. p2p.WithMetrics(p2pMetrics),
  651. p2p.SwitchPeerFilters(peerFilters...),
  652. p2p.SwitchConnFilters(connFilters...),
  653. )
  654. sw.SetLogger(p2pLogger)
  655. if config.Mode != cfg.ModeSeed {
  656. sw.AddReactor("MEMPOOL", mempoolReactor)
  657. sw.AddReactor("BLOCKCHAIN", bcReactor)
  658. sw.AddReactor("CONSENSUS", consensusReactor)
  659. sw.AddReactor("EVIDENCE", evidenceReactor)
  660. sw.AddReactor("STATESYNC", stateSyncReactor)
  661. }
  662. sw.SetNodeInfo(nodeInfo)
  663. sw.SetNodeKey(nodeKey)
  664. // XXX: needed to support old/new P2P stacks
  665. sw.PutChannelDescsIntoTransport()
  666. p2pLogger.Info("P2P Node ID", "ID", nodeKey.ID, "file", config.NodeKeyFile())
  667. return sw
  668. }
  669. func createAddrBookAndSetOnSwitch(config *cfg.Config, sw *p2p.Switch,
  670. p2pLogger log.Logger, nodeKey p2p.NodeKey) (pex.AddrBook, error) {
  671. addrBook := pex.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict)
  672. addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile()))
  673. // Add ourselves to addrbook to prevent dialing ourselves
  674. if config.P2P.ExternalAddress != "" {
  675. addr, err := p2p.NewNetAddressString(p2p.IDAddressString(nodeKey.ID, config.P2P.ExternalAddress))
  676. if err != nil {
  677. return nil, fmt.Errorf("p2p.external_address is incorrect: %w", err)
  678. }
  679. addrBook.AddOurAddress(addr)
  680. }
  681. if config.P2P.ListenAddress != "" {
  682. addr, err := p2p.NewNetAddressString(p2p.IDAddressString(nodeKey.ID, config.P2P.ListenAddress))
  683. if err != nil {
  684. return nil, fmt.Errorf("p2p.laddr is incorrect: %w", err)
  685. }
  686. addrBook.AddOurAddress(addr)
  687. }
  688. sw.SetAddrBook(addrBook)
  689. return addrBook, nil
  690. }
  691. func createPEXReactorAndAddToSwitch(addrBook pex.AddrBook, config *cfg.Config,
  692. sw *p2p.Switch, logger log.Logger) *pex.Reactor {
  693. reactorConfig := &pex.ReactorConfig{
  694. Seeds: splitAndTrimEmpty(config.P2P.Seeds, ",", " "),
  695. SeedMode: config.Mode == cfg.ModeSeed,
  696. // See consensus/reactor.go: blocksToContributeToBecomeGoodPeer 10000
  697. // blocks assuming 10s blocks ~ 28 hours.
  698. // TODO (melekes): make it dynamic based on the actual block latencies
  699. // from the live network.
  700. // https://github.com/tendermint/tendermint/issues/3523
  701. SeedDisconnectWaitPeriod: 28 * time.Hour,
  702. PersistentPeersMaxDialPeriod: config.P2P.PersistentPeersMaxDialPeriod,
  703. }
  704. // TODO persistent peers ? so we can have their DNS addrs saved
  705. pexReactor := pex.NewReactor(addrBook, reactorConfig)
  706. pexReactor.SetLogger(logger.With("module", "pex"))
  707. sw.AddReactor("PEX", pexReactor)
  708. return pexReactor
  709. }
  710. func createPEXReactorV2(
  711. config *cfg.Config,
  712. logger log.Logger,
  713. peerManager *p2p.PeerManager,
  714. router *p2p.Router,
  715. ) (*pex.ReactorV2, error) {
  716. channel, err := router.OpenChannel(p2p.ChannelID(pex.PexChannel), &protop2p.PexMessage{}, 4096)
  717. if err != nil {
  718. return nil, err
  719. }
  720. peerUpdates := peerManager.Subscribe()
  721. return pex.NewReactorV2(logger, peerManager, channel, peerUpdates), nil
  722. }
  723. // startStateSync starts an asynchronous state sync process, then switches to fast sync mode.
  724. func startStateSync(ssR *statesync.Reactor, bcR fastSyncReactor, conR *cs.Reactor,
  725. stateProvider statesync.StateProvider, config *cfg.StateSyncConfig, fastSync bool,
  726. stateStore sm.Store, blockStore *store.BlockStore, state sm.State) error {
  727. ssR.Logger.Info("Starting state sync")
  728. if stateProvider == nil {
  729. var err error
  730. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  731. defer cancel()
  732. stateProvider, err = statesync.NewLightClientStateProvider(
  733. ctx,
  734. state.ChainID, state.Version, state.InitialHeight,
  735. config.RPCServers, light.TrustOptions{
  736. Period: config.TrustPeriod,
  737. Height: config.TrustHeight,
  738. Hash: config.TrustHashBytes(),
  739. }, ssR.Logger.With("module", "light"))
  740. if err != nil {
  741. return fmt.Errorf("failed to set up light client state provider: %w", err)
  742. }
  743. }
  744. go func() {
  745. state, commit, err := ssR.Sync(stateProvider, config.DiscoveryTime)
  746. if err != nil {
  747. ssR.Logger.Error("State sync failed", "err", err)
  748. return
  749. }
  750. err = stateStore.Bootstrap(state)
  751. if err != nil {
  752. ssR.Logger.Error("Failed to bootstrap node with new state", "err", err)
  753. return
  754. }
  755. err = blockStore.SaveSeenCommit(state.LastBlockHeight, commit)
  756. if err != nil {
  757. ssR.Logger.Error("Failed to store last seen commit", "err", err)
  758. return
  759. }
  760. if fastSync {
  761. // FIXME Very ugly to have these metrics bleed through here.
  762. conR.Metrics.StateSyncing.Set(0)
  763. conR.Metrics.FastSyncing.Set(1)
  764. err = bcR.SwitchToFastSync(state)
  765. if err != nil {
  766. ssR.Logger.Error("Failed to switch to fast sync", "err", err)
  767. return
  768. }
  769. } else {
  770. conR.SwitchToConsensus(state, true)
  771. }
  772. }()
  773. return nil
  774. }
  775. // NewSeedNode returns a new seed node, containing only p2p, pex reactor
  776. func NewSeedNode(config *cfg.Config,
  777. dbProvider DBProvider,
  778. nodeKey p2p.NodeKey,
  779. genesisDocProvider GenesisDocProvider,
  780. logger log.Logger,
  781. options ...Option) (*Node, error) {
  782. genDoc, err := genesisDocProvider()
  783. if err != nil {
  784. return nil, err
  785. }
  786. state, err := sm.MakeGenesisState(genDoc)
  787. if err != nil {
  788. return nil, err
  789. }
  790. nodeInfo, err := makeSeedNodeInfo(config, nodeKey, genDoc, state)
  791. if err != nil {
  792. return nil, err
  793. }
  794. // Setup Transport and Switch.
  795. p2pMetrics := p2p.PrometheusMetrics(config.Instrumentation.Namespace, "chain_id", genDoc.ChainID)
  796. p2pLogger := logger.With("module", "p2p")
  797. transport := createTransport(p2pLogger, config)
  798. sw := createSwitch(
  799. config, transport, p2pMetrics, nil, nil,
  800. nil, nil, nil, nil, nodeInfo, nodeKey, p2pLogger,
  801. )
  802. err = sw.AddPersistentPeers(splitAndTrimEmpty(config.P2P.PersistentPeers, ",", " "))
  803. if err != nil {
  804. return nil, fmt.Errorf("could not add peers from persistent_peers field: %w", err)
  805. }
  806. err = sw.AddUnconditionalPeerIDs(splitAndTrimEmpty(config.P2P.UnconditionalPeerIDs, ",", " "))
  807. if err != nil {
  808. return nil, fmt.Errorf("could not add peer ids from unconditional_peer_ids field: %w", err)
  809. }
  810. addrBook, err := createAddrBookAndSetOnSwitch(config, sw, p2pLogger, nodeKey)
  811. if err != nil {
  812. return nil, fmt.Errorf("could not create addrbook: %w", err)
  813. }
  814. peerManager, err := createPeerManager(config, dbProvider, p2pLogger, nodeKey.ID)
  815. if err != nil {
  816. return nil, fmt.Errorf("failed to create peer manager: %w", err)
  817. }
  818. router, err := createRouter(p2pLogger, p2pMetrics, nodeInfo, nodeKey.PrivKey,
  819. peerManager, transport, getRouterConfig(config, nil))
  820. if err != nil {
  821. return nil, fmt.Errorf("failed to create router: %w", err)
  822. }
  823. // start the pex reactor
  824. pexReactor := createPEXReactorAndAddToSwitch(addrBook, config, sw, logger)
  825. pexReactorV2, err := createPEXReactorV2(config, logger, peerManager, router)
  826. if err != nil {
  827. return nil, err
  828. }
  829. if config.RPC.PprofListenAddress != "" {
  830. go func() {
  831. logger.Info("Starting pprof server", "laddr", config.RPC.PprofListenAddress)
  832. logger.Error("pprof server error", "err", http.ListenAndServe(config.RPC.PprofListenAddress, nil))
  833. }()
  834. }
  835. node := &Node{
  836. config: config,
  837. genesisDoc: genDoc,
  838. transport: transport,
  839. sw: sw,
  840. addrBook: addrBook,
  841. nodeInfo: nodeInfo,
  842. nodeKey: nodeKey,
  843. peerManager: peerManager,
  844. router: router,
  845. pexReactor: pexReactor,
  846. pexReactorV2: pexReactorV2,
  847. }
  848. node.BaseService = *service.NewBaseService(logger, "SeedNode", node)
  849. for _, option := range options {
  850. option(node)
  851. }
  852. return node, nil
  853. }
  854. // NewNode returns a new, ready to go, Tendermint Node.
  855. func NewNode(config *cfg.Config,
  856. privValidator types.PrivValidator,
  857. nodeKey p2p.NodeKey,
  858. clientCreator proxy.ClientCreator,
  859. genesisDocProvider GenesisDocProvider,
  860. dbProvider DBProvider,
  861. metricsProvider MetricsProvider,
  862. logger log.Logger,
  863. options ...Option) (*Node, error) {
  864. blockStore, stateDB, err := initDBs(config, dbProvider)
  865. if err != nil {
  866. return nil, err
  867. }
  868. stateStore := sm.NewStore(stateDB)
  869. state, genDoc, err := LoadStateFromDBOrGenesisDocProvider(stateDB, genesisDocProvider)
  870. if err != nil {
  871. return nil, err
  872. }
  873. // Create the proxyApp and establish connections to the ABCI app (consensus, mempool, query).
  874. proxyApp, err := createAndStartProxyAppConns(clientCreator, logger)
  875. if err != nil {
  876. return nil, err
  877. }
  878. // EventBus and IndexerService must be started before the handshake because
  879. // we might need to index the txs of the replayed block as this might not have happened
  880. // when the node stopped last time (i.e. the node stopped after it saved the block
  881. // but before it indexed the txs, or, endblocker panicked)
  882. eventBus, err := createAndStartEventBus(logger)
  883. if err != nil {
  884. return nil, err
  885. }
  886. indexerService, txIndexer, blockIndexer, err := createAndStartIndexerService(config, dbProvider, eventBus, logger)
  887. if err != nil {
  888. return nil, err
  889. }
  890. // If an address is provided, listen on the socket for a connection from an
  891. // external signing process.
  892. if config.PrivValidatorListenAddr != "" {
  893. protocol, _ := tmnet.ProtocolAndAddress(config.PrivValidatorListenAddr)
  894. // FIXME: we should start services inside OnStart
  895. switch protocol {
  896. case "grpc":
  897. privValidator, err = createAndStartPrivValidatorGRPCClient(config, genDoc.ChainID, logger)
  898. if err != nil {
  899. return nil, fmt.Errorf("error with private validator grpc client: %w", err)
  900. }
  901. default:
  902. privValidator, err = createAndStartPrivValidatorSocketClient(config.PrivValidatorListenAddr, genDoc.ChainID, logger)
  903. if err != nil {
  904. return nil, fmt.Errorf("error with private validator socket client: %w", err)
  905. }
  906. }
  907. }
  908. var pubKey crypto.PubKey
  909. if config.Mode == cfg.ModeValidator {
  910. pubKey, err = privValidator.GetPubKey(context.TODO())
  911. if err != nil {
  912. return nil, fmt.Errorf("can't get pubkey: %w", err)
  913. }
  914. if pubKey == nil {
  915. return nil, errors.New("could not retrieve public key from private validator")
  916. }
  917. }
  918. // Determine whether we should attempt state sync.
  919. stateSync := config.StateSync.Enable && !onlyValidatorIsUs(state, pubKey)
  920. if stateSync && state.LastBlockHeight > 0 {
  921. logger.Info("Found local state with non-zero height, skipping state sync")
  922. stateSync = false
  923. }
  924. // Create the handshaker, which calls RequestInfo, sets the AppVersion on the state,
  925. // and replays any blocks as necessary to sync tendermint with the app.
  926. consensusLogger := logger.With("module", "consensus")
  927. if !stateSync {
  928. if err := doHandshake(stateStore, state, blockStore, genDoc, eventBus, proxyApp, consensusLogger); err != nil {
  929. return nil, err
  930. }
  931. // Reload the state. It will have the Version.Consensus.App set by the
  932. // Handshake, and may have other modifications as well (ie. depending on
  933. // what happened during block replay).
  934. state, err = stateStore.Load()
  935. if err != nil {
  936. return nil, fmt.Errorf("cannot load state: %w", err)
  937. }
  938. }
  939. // Determine whether we should do fast sync. This must happen after the handshake, since the
  940. // app may modify the validator set, specifying ourself as the only validator.
  941. fastSync := config.FastSyncMode && !onlyValidatorIsUs(state, pubKey)
  942. logNodeStartupInfo(state, pubKey, logger, consensusLogger, config.Mode)
  943. // TODO: Fetch and provide real options and do proper p2p bootstrapping.
  944. // TODO: Use a persistent peer database.
  945. nodeInfo, err := makeNodeInfo(config, nodeKey, txIndexer, genDoc, state)
  946. if err != nil {
  947. return nil, err
  948. }
  949. p2pLogger := logger.With("module", "p2p")
  950. transport := createTransport(p2pLogger, config)
  951. peerManager, err := createPeerManager(config, dbProvider, p2pLogger, nodeKey.ID)
  952. if err != nil {
  953. return nil, fmt.Errorf("failed to create peer manager: %w", err)
  954. }
  955. csMetrics, p2pMetrics, memplMetrics, smMetrics := metricsProvider(genDoc.ChainID)
  956. router, err := createRouter(p2pLogger, p2pMetrics, nodeInfo, nodeKey.PrivKey,
  957. peerManager, transport, getRouterConfig(config, proxyApp))
  958. if err != nil {
  959. return nil, fmt.Errorf("failed to create router: %w", err)
  960. }
  961. mpReactorShim, mpReactor, mempool := createMempoolReactor(
  962. config, proxyApp, state, memplMetrics, peerManager, router, logger,
  963. )
  964. evReactorShim, evReactor, evPool, err := createEvidenceReactor(
  965. config, dbProvider, stateDB, blockStore, peerManager, router, logger,
  966. )
  967. if err != nil {
  968. return nil, err
  969. }
  970. // make block executor for consensus and blockchain reactors to execute blocks
  971. blockExec := sm.NewBlockExecutor(
  972. stateStore,
  973. logger.With("module", "state"),
  974. proxyApp.Consensus(),
  975. mempool,
  976. evPool,
  977. sm.BlockExecutorWithMetrics(smMetrics),
  978. )
  979. csReactorShim, csReactor, csState := createConsensusReactor(
  980. config, state, blockExec, blockStore, mempool, evPool,
  981. privValidator, csMetrics, stateSync || fastSync, eventBus,
  982. peerManager, router, consensusLogger,
  983. )
  984. // Create the blockchain reactor. Note, we do not start fast sync if we're
  985. // doing a state sync first.
  986. bcReactorShim, bcReactor, err := createBlockchainReactor(
  987. logger, config, state, blockExec, blockStore, csReactor,
  988. peerManager, router, fastSync && !stateSync,
  989. )
  990. if err != nil {
  991. return nil, fmt.Errorf("could not create blockchain reactor: %w", err)
  992. }
  993. // TODO: Remove this once the switch is removed.
  994. var bcReactorForSwitch p2p.Reactor
  995. if bcReactorShim != nil {
  996. bcReactorForSwitch = bcReactorShim
  997. } else {
  998. bcReactorForSwitch = bcReactor.(p2p.Reactor)
  999. }
  1000. // Make ConsensusReactor. Don't enable fully if doing a state sync and/or fast sync first.
  1001. // FIXME We need to update metrics here, since other reactors don't have access to them.
  1002. if stateSync {
  1003. csMetrics.StateSyncing.Set(1)
  1004. } else if fastSync {
  1005. csMetrics.FastSyncing.Set(1)
  1006. }
  1007. // Set up state sync reactor, and schedule a sync if requested.
  1008. // FIXME The way we do phased startups (e.g. replay -> fast sync -> consensus) is very messy,
  1009. // we should clean this whole thing up. See:
  1010. // https://github.com/tendermint/tendermint/issues/4644
  1011. var (
  1012. stateSyncReactor *statesync.Reactor
  1013. stateSyncReactorShim *p2p.ReactorShim
  1014. channels map[p2p.ChannelID]*p2p.Channel
  1015. peerUpdates *p2p.PeerUpdates
  1016. )
  1017. stateSyncReactorShim = p2p.NewReactorShim(logger.With("module", "statesync"), "StateSyncShim", statesync.ChannelShims)
  1018. if config.P2P.DisableLegacy {
  1019. channels = makeChannelsFromShims(router, statesync.ChannelShims)
  1020. peerUpdates = peerManager.Subscribe()
  1021. } else {
  1022. channels = getChannelsFromShim(stateSyncReactorShim)
  1023. peerUpdates = stateSyncReactorShim.PeerUpdates
  1024. }
  1025. stateSyncReactor = statesync.NewReactor(
  1026. stateSyncReactorShim.Logger,
  1027. proxyApp.Snapshot(),
  1028. proxyApp.Query(),
  1029. channels[statesync.SnapshotChannel],
  1030. channels[statesync.ChunkChannel],
  1031. peerUpdates,
  1032. config.StateSync.TempDir,
  1033. )
  1034. router.AddChannelDescriptors(mpReactorShim.GetChannels())
  1035. router.AddChannelDescriptors(bcReactorForSwitch.GetChannels())
  1036. router.AddChannelDescriptors(csReactorShim.GetChannels())
  1037. router.AddChannelDescriptors(evReactorShim.GetChannels())
  1038. router.AddChannelDescriptors(stateSyncReactorShim.GetChannels())
  1039. // setup Transport and Switch
  1040. sw := createSwitch(
  1041. config, transport, p2pMetrics, mpReactorShim, bcReactorForSwitch,
  1042. stateSyncReactorShim, csReactorShim, evReactorShim, proxyApp, nodeInfo, nodeKey, p2pLogger,
  1043. )
  1044. err = sw.AddPersistentPeers(splitAndTrimEmpty(config.P2P.PersistentPeers, ",", " "))
  1045. if err != nil {
  1046. return nil, fmt.Errorf("could not add peers from persistent-peers field: %w", err)
  1047. }
  1048. err = sw.AddUnconditionalPeerIDs(splitAndTrimEmpty(config.P2P.UnconditionalPeerIDs, ",", " "))
  1049. if err != nil {
  1050. return nil, fmt.Errorf("could not add peer ids from unconditional_peer_ids field: %w", err)
  1051. }
  1052. addrBook, err := createAddrBookAndSetOnSwitch(config, sw, p2pLogger, nodeKey)
  1053. if err != nil {
  1054. return nil, fmt.Errorf("could not create addrbook: %w", err)
  1055. }
  1056. // Optionally, start the pex reactor
  1057. //
  1058. // TODO:
  1059. //
  1060. // We need to set Seeds and PersistentPeers on the switch,
  1061. // since it needs to be able to use these (and their DNS names)
  1062. // even if the PEX is off. We can include the DNS name in the NetAddress,
  1063. // but it would still be nice to have a clear list of the current "PersistentPeers"
  1064. // somewhere that we can return with net_info.
  1065. //
  1066. // If PEX is on, it should handle dialing the seeds. Otherwise the switch does it.
  1067. // Note we currently use the addrBook regardless at least for AddOurAddress
  1068. var (
  1069. pexReactor *pex.Reactor
  1070. pexReactorV2 *pex.ReactorV2
  1071. )
  1072. if config.P2P.PexReactor {
  1073. pexReactor = createPEXReactorAndAddToSwitch(addrBook, config, sw, logger)
  1074. pexReactorV2, err = createPEXReactorV2(config, logger, peerManager, router)
  1075. if err != nil {
  1076. return nil, err
  1077. }
  1078. router.AddChannelDescriptors(pexReactor.GetChannels())
  1079. }
  1080. if config.RPC.PprofListenAddress != "" {
  1081. go func() {
  1082. logger.Info("Starting pprof server", "laddr", config.RPC.PprofListenAddress)
  1083. logger.Error("pprof server error", "err", http.ListenAndServe(config.RPC.PprofListenAddress, nil))
  1084. }()
  1085. }
  1086. node := &Node{
  1087. config: config,
  1088. genesisDoc: genDoc,
  1089. privValidator: privValidator,
  1090. transport: transport,
  1091. sw: sw,
  1092. peerManager: peerManager,
  1093. router: router,
  1094. addrBook: addrBook,
  1095. nodeInfo: nodeInfo,
  1096. nodeKey: nodeKey,
  1097. stateStore: stateStore,
  1098. blockStore: blockStore,
  1099. bcReactor: bcReactor,
  1100. mempoolReactor: mpReactor,
  1101. mempool: mempool,
  1102. consensusState: csState,
  1103. consensusReactor: csReactor,
  1104. stateSyncReactor: stateSyncReactor,
  1105. stateSync: stateSync,
  1106. stateSyncGenesis: state, // Shouldn't be necessary, but need a way to pass the genesis state
  1107. pexReactor: pexReactor,
  1108. pexReactorV2: pexReactorV2,
  1109. evidenceReactor: evReactor,
  1110. evidencePool: evPool,
  1111. proxyApp: proxyApp,
  1112. txIndexer: txIndexer,
  1113. indexerService: indexerService,
  1114. blockIndexer: blockIndexer,
  1115. eventBus: eventBus,
  1116. }
  1117. node.BaseService = *service.NewBaseService(logger, "Node", node)
  1118. for _, option := range options {
  1119. option(node)
  1120. }
  1121. return node, nil
  1122. }
  1123. // OnStart starts the Node. It implements service.Service.
  1124. func (n *Node) OnStart() error {
  1125. now := tmtime.Now()
  1126. genTime := n.genesisDoc.GenesisTime
  1127. if genTime.After(now) {
  1128. n.Logger.Info("Genesis time is in the future. Sleeping until then...", "genTime", genTime)
  1129. time.Sleep(genTime.Sub(now))
  1130. }
  1131. // Add private IDs to addrbook to block those peers being added
  1132. n.addrBook.AddPrivateIDs(splitAndTrimEmpty(n.config.P2P.PrivatePeerIDs, ",", " "))
  1133. // Start the RPC server before the P2P server
  1134. // so we can eg. receive txs for the first block
  1135. if n.config.RPC.ListenAddress != "" && n.config.Mode != cfg.ModeSeed {
  1136. listeners, err := n.startRPC()
  1137. if err != nil {
  1138. return err
  1139. }
  1140. n.rpcListeners = listeners
  1141. }
  1142. if n.config.Instrumentation.Prometheus &&
  1143. n.config.Instrumentation.PrometheusListenAddr != "" {
  1144. n.prometheusSrv = n.startPrometheusServer(n.config.Instrumentation.PrometheusListenAddr)
  1145. }
  1146. // Start the mempool.
  1147. if n.config.Mempool.WalEnabled() {
  1148. err := n.mempool.InitWAL()
  1149. if err != nil {
  1150. return fmt.Errorf("init mempool WAL: %w", err)
  1151. }
  1152. }
  1153. // Start the transport.
  1154. addr, err := p2p.NewNetAddressString(p2p.IDAddressString(n.nodeKey.ID, n.config.P2P.ListenAddress))
  1155. if err != nil {
  1156. return err
  1157. }
  1158. if err := n.transport.Listen(addr.Endpoint()); err != nil {
  1159. return err
  1160. }
  1161. n.isListening = true
  1162. n.Logger.Info("p2p service", "legacy_enabled", !n.config.P2P.DisableLegacy)
  1163. if n.config.P2P.DisableLegacy {
  1164. err = n.router.Start()
  1165. } else {
  1166. err = n.sw.Start()
  1167. }
  1168. if err != nil {
  1169. return err
  1170. }
  1171. if n.config.Mode != cfg.ModeSeed {
  1172. if n.config.FastSync.Version == cfg.BlockchainV0 {
  1173. // Start the real blockchain reactor separately since the switch uses the shim.
  1174. if err := n.bcReactor.Start(); err != nil {
  1175. return err
  1176. }
  1177. }
  1178. // Start the real consensus reactor separately since the switch uses the shim.
  1179. if err := n.consensusReactor.Start(); err != nil {
  1180. return err
  1181. }
  1182. // Start the real state sync reactor separately since the switch uses the shim.
  1183. if err := n.stateSyncReactor.Start(); err != nil {
  1184. return err
  1185. }
  1186. // Start the real mempool reactor separately since the switch uses the shim.
  1187. if err := n.mempoolReactor.Start(); err != nil {
  1188. return err
  1189. }
  1190. // Start the real evidence reactor separately since the switch uses the shim.
  1191. if err := n.evidenceReactor.Start(); err != nil {
  1192. return err
  1193. }
  1194. }
  1195. if n.config.P2P.DisableLegacy && n.pexReactorV2 != nil {
  1196. if err := n.pexReactorV2.Start(); err != nil {
  1197. return err
  1198. }
  1199. }
  1200. // Always connect to persistent peers
  1201. err = n.sw.DialPeersAsync(splitAndTrimEmpty(n.config.P2P.PersistentPeers, ",", " "))
  1202. if err != nil {
  1203. return fmt.Errorf("could not dial peers from persistent-peers field: %w", err)
  1204. }
  1205. // Run state sync
  1206. if n.stateSync {
  1207. bcR, ok := n.bcReactor.(fastSyncReactor)
  1208. if !ok {
  1209. return fmt.Errorf("this blockchain reactor does not support switching from state sync")
  1210. }
  1211. err := startStateSync(n.stateSyncReactor, bcR, n.consensusReactor, n.stateSyncProvider,
  1212. n.config.StateSync, n.config.FastSyncMode, n.stateStore, n.blockStore, n.stateSyncGenesis)
  1213. if err != nil {
  1214. return fmt.Errorf("failed to start state sync: %w", err)
  1215. }
  1216. }
  1217. return nil
  1218. }
  1219. // OnStop stops the Node. It implements service.Service.
  1220. func (n *Node) OnStop() {
  1221. n.BaseService.OnStop()
  1222. n.Logger.Info("Stopping Node")
  1223. // first stop the non-reactor services
  1224. if err := n.eventBus.Stop(); err != nil {
  1225. n.Logger.Error("Error closing eventBus", "err", err)
  1226. }
  1227. if err := n.indexerService.Stop(); err != nil {
  1228. n.Logger.Error("Error closing indexerService", "err", err)
  1229. }
  1230. if n.config.Mode != cfg.ModeSeed {
  1231. // now stop the reactors
  1232. if n.config.FastSync.Version == "v0" {
  1233. // Stop the real blockchain reactor separately since the switch uses the shim.
  1234. if err := n.bcReactor.Stop(); err != nil {
  1235. n.Logger.Error("failed to stop the blockchain reactor", "err", err)
  1236. }
  1237. }
  1238. // Stop the real consensus reactor separately since the switch uses the shim.
  1239. if err := n.consensusReactor.Stop(); err != nil {
  1240. n.Logger.Error("failed to stop the consensus reactor", "err", err)
  1241. }
  1242. // Stop the real state sync reactor separately since the switch uses the shim.
  1243. if err := n.stateSyncReactor.Stop(); err != nil {
  1244. n.Logger.Error("failed to stop the state sync reactor", "err", err)
  1245. }
  1246. // Stop the real mempool reactor separately since the switch uses the shim.
  1247. if err := n.mempoolReactor.Stop(); err != nil {
  1248. n.Logger.Error("failed to stop the mempool reactor", "err", err)
  1249. }
  1250. // Stop the real evidence reactor separately since the switch uses the shim.
  1251. if err := n.evidenceReactor.Stop(); err != nil {
  1252. n.Logger.Error("failed to stop the evidence reactor", "err", err)
  1253. }
  1254. }
  1255. if n.config.P2P.DisableLegacy && n.pexReactorV2 != nil {
  1256. if err := n.pexReactorV2.Stop(); err != nil {
  1257. n.Logger.Error("failed to stop the PEX v2 reactor", "err", err)
  1258. }
  1259. }
  1260. if n.config.P2P.DisableLegacy {
  1261. if err := n.router.Stop(); err != nil {
  1262. n.Logger.Error("failed to stop router", "err", err)
  1263. }
  1264. } else {
  1265. if err := n.sw.Stop(); err != nil {
  1266. n.Logger.Error("failed to stop switch", "err", err)
  1267. }
  1268. }
  1269. // stop mempool WAL
  1270. if n.config.Mempool.WalEnabled() {
  1271. n.mempool.CloseWAL()
  1272. }
  1273. if err := n.transport.Close(); err != nil {
  1274. n.Logger.Error("Error closing transport", "err", err)
  1275. }
  1276. n.isListening = false
  1277. // finally stop the listeners / external services
  1278. for _, l := range n.rpcListeners {
  1279. n.Logger.Info("Closing rpc listener", "listener", l)
  1280. if err := l.Close(); err != nil {
  1281. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  1282. }
  1283. }
  1284. if pvsc, ok := n.privValidator.(service.Service); ok {
  1285. if err := pvsc.Stop(); err != nil {
  1286. n.Logger.Error("Error closing private validator", "err", err)
  1287. }
  1288. }
  1289. if n.prometheusSrv != nil {
  1290. if err := n.prometheusSrv.Shutdown(context.Background()); err != nil {
  1291. // Error from closing listeners, or context timeout:
  1292. n.Logger.Error("Prometheus HTTP server Shutdown", "err", err)
  1293. }
  1294. }
  1295. }
  1296. // ConfigureRPC makes sure RPC has all the objects it needs to operate.
  1297. func (n *Node) ConfigureRPC() error {
  1298. rpcCoreEnv := rpccore.Environment{
  1299. ProxyAppQuery: n.proxyApp.Query(),
  1300. ProxyAppMempool: n.proxyApp.Mempool(),
  1301. StateStore: n.stateStore,
  1302. BlockStore: n.blockStore,
  1303. EvidencePool: n.evidencePool,
  1304. ConsensusState: n.consensusState,
  1305. P2PPeers: n.sw,
  1306. P2PTransport: n,
  1307. GenDoc: n.genesisDoc,
  1308. TxIndexer: n.txIndexer,
  1309. BlockIndexer: n.blockIndexer,
  1310. ConsensusReactor: n.consensusReactor,
  1311. EventBus: n.eventBus,
  1312. Mempool: n.mempool,
  1313. Logger: n.Logger.With("module", "rpc"),
  1314. Config: *n.config.RPC,
  1315. }
  1316. if n.config.Mode == cfg.ModeValidator {
  1317. pubKey, err := n.privValidator.GetPubKey(context.TODO())
  1318. if pubKey == nil || err != nil {
  1319. return fmt.Errorf("can't get pubkey: %w", err)
  1320. }
  1321. rpcCoreEnv.PubKey = pubKey
  1322. }
  1323. rpccore.SetEnvironment(&rpcCoreEnv)
  1324. return nil
  1325. }
  1326. func (n *Node) startRPC() ([]net.Listener, error) {
  1327. err := n.ConfigureRPC()
  1328. if err != nil {
  1329. return nil, err
  1330. }
  1331. listenAddrs := splitAndTrimEmpty(n.config.RPC.ListenAddress, ",", " ")
  1332. if n.config.RPC.Unsafe {
  1333. rpccore.AddUnsafeRoutes()
  1334. }
  1335. config := rpcserver.DefaultConfig()
  1336. config.MaxBodyBytes = n.config.RPC.MaxBodyBytes
  1337. config.MaxHeaderBytes = n.config.RPC.MaxHeaderBytes
  1338. config.MaxOpenConnections = n.config.RPC.MaxOpenConnections
  1339. // If necessary adjust global WriteTimeout to ensure it's greater than
  1340. // TimeoutBroadcastTxCommit.
  1341. // See https://github.com/tendermint/tendermint/issues/3435
  1342. if config.WriteTimeout <= n.config.RPC.TimeoutBroadcastTxCommit {
  1343. config.WriteTimeout = n.config.RPC.TimeoutBroadcastTxCommit + 1*time.Second
  1344. }
  1345. // we may expose the rpc over both a unix and tcp socket
  1346. listeners := make([]net.Listener, len(listenAddrs))
  1347. for i, listenAddr := range listenAddrs {
  1348. mux := http.NewServeMux()
  1349. rpcLogger := n.Logger.With("module", "rpc-server")
  1350. wmLogger := rpcLogger.With("protocol", "websocket")
  1351. wm := rpcserver.NewWebsocketManager(rpccore.Routes,
  1352. rpcserver.OnDisconnect(func(remoteAddr string) {
  1353. err := n.eventBus.UnsubscribeAll(context.Background(), remoteAddr)
  1354. if err != nil && err != tmpubsub.ErrSubscriptionNotFound {
  1355. wmLogger.Error("Failed to unsubscribe addr from events", "addr", remoteAddr, "err", err)
  1356. }
  1357. }),
  1358. rpcserver.ReadLimit(config.MaxBodyBytes),
  1359. )
  1360. wm.SetLogger(wmLogger)
  1361. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  1362. rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger)
  1363. listener, err := rpcserver.Listen(
  1364. listenAddr,
  1365. config,
  1366. )
  1367. if err != nil {
  1368. return nil, err
  1369. }
  1370. var rootHandler http.Handler = mux
  1371. if n.config.RPC.IsCorsEnabled() {
  1372. corsMiddleware := cors.New(cors.Options{
  1373. AllowedOrigins: n.config.RPC.CORSAllowedOrigins,
  1374. AllowedMethods: n.config.RPC.CORSAllowedMethods,
  1375. AllowedHeaders: n.config.RPC.CORSAllowedHeaders,
  1376. })
  1377. rootHandler = corsMiddleware.Handler(mux)
  1378. }
  1379. if n.config.RPC.IsTLSEnabled() {
  1380. go func() {
  1381. if err := rpcserver.ServeTLS(
  1382. listener,
  1383. rootHandler,
  1384. n.config.RPC.CertFile(),
  1385. n.config.RPC.KeyFile(),
  1386. rpcLogger,
  1387. config,
  1388. ); err != nil {
  1389. n.Logger.Error("Error serving server with TLS", "err", err)
  1390. }
  1391. }()
  1392. } else {
  1393. go func() {
  1394. if err := rpcserver.Serve(
  1395. listener,
  1396. rootHandler,
  1397. rpcLogger,
  1398. config,
  1399. ); err != nil {
  1400. n.Logger.Error("Error serving server", "err", err)
  1401. }
  1402. }()
  1403. }
  1404. listeners[i] = listener
  1405. }
  1406. // we expose a simplified api over grpc for convenience to app devs
  1407. grpcListenAddr := n.config.RPC.GRPCListenAddress
  1408. if grpcListenAddr != "" {
  1409. config := rpcserver.DefaultConfig()
  1410. config.MaxBodyBytes = n.config.RPC.MaxBodyBytes
  1411. config.MaxHeaderBytes = n.config.RPC.MaxHeaderBytes
  1412. // NOTE: GRPCMaxOpenConnections is used, not MaxOpenConnections
  1413. config.MaxOpenConnections = n.config.RPC.GRPCMaxOpenConnections
  1414. // If necessary adjust global WriteTimeout to ensure it's greater than
  1415. // TimeoutBroadcastTxCommit.
  1416. // See https://github.com/tendermint/tendermint/issues/3435
  1417. if config.WriteTimeout <= n.config.RPC.TimeoutBroadcastTxCommit {
  1418. config.WriteTimeout = n.config.RPC.TimeoutBroadcastTxCommit + 1*time.Second
  1419. }
  1420. listener, err := rpcserver.Listen(grpcListenAddr, config)
  1421. if err != nil {
  1422. return nil, err
  1423. }
  1424. go func() {
  1425. if err := grpccore.StartGRPCServer(listener); err != nil {
  1426. n.Logger.Error("Error starting gRPC server", "err", err)
  1427. }
  1428. }()
  1429. listeners = append(listeners, listener)
  1430. }
  1431. return listeners, nil
  1432. }
  1433. // startPrometheusServer starts a Prometheus HTTP server, listening for metrics
  1434. // collectors on addr.
  1435. func (n *Node) startPrometheusServer(addr string) *http.Server {
  1436. srv := &http.Server{
  1437. Addr: addr,
  1438. Handler: promhttp.InstrumentMetricHandler(
  1439. prometheus.DefaultRegisterer, promhttp.HandlerFor(
  1440. prometheus.DefaultGatherer,
  1441. promhttp.HandlerOpts{MaxRequestsInFlight: n.config.Instrumentation.MaxOpenConnections},
  1442. ),
  1443. ),
  1444. }
  1445. go func() {
  1446. if err := srv.ListenAndServe(); err != http.ErrServerClosed {
  1447. // Error starting or closing listener:
  1448. n.Logger.Error("Prometheus HTTP server ListenAndServe", "err", err)
  1449. }
  1450. }()
  1451. return srv
  1452. }
  1453. // Switch returns the Node's Switch.
  1454. func (n *Node) Switch() *p2p.Switch {
  1455. return n.sw
  1456. }
  1457. // BlockStore returns the Node's BlockStore.
  1458. func (n *Node) BlockStore() *store.BlockStore {
  1459. return n.blockStore
  1460. }
  1461. // ConsensusState returns the Node's ConsensusState.
  1462. func (n *Node) ConsensusState() *cs.State {
  1463. return n.consensusState
  1464. }
  1465. // ConsensusReactor returns the Node's ConsensusReactor.
  1466. func (n *Node) ConsensusReactor() *cs.Reactor {
  1467. return n.consensusReactor
  1468. }
  1469. // MempoolReactor returns the Node's mempool reactor.
  1470. func (n *Node) MempoolReactor() *mempl.Reactor {
  1471. return n.mempoolReactor
  1472. }
  1473. // Mempool returns the Node's mempool.
  1474. func (n *Node) Mempool() mempl.Mempool {
  1475. return n.mempool
  1476. }
  1477. // PEXReactor returns the Node's PEXReactor. It returns nil if PEX is disabled.
  1478. func (n *Node) PEXReactor() *pex.Reactor {
  1479. return n.pexReactor
  1480. }
  1481. // EvidencePool returns the Node's EvidencePool.
  1482. func (n *Node) EvidencePool() *evidence.Pool {
  1483. return n.evidencePool
  1484. }
  1485. // EventBus returns the Node's EventBus.
  1486. func (n *Node) EventBus() *types.EventBus {
  1487. return n.eventBus
  1488. }
  1489. // PrivValidator returns the Node's PrivValidator.
  1490. // XXX: for convenience only!
  1491. func (n *Node) PrivValidator() types.PrivValidator {
  1492. return n.privValidator
  1493. }
  1494. // GenesisDoc returns the Node's GenesisDoc.
  1495. func (n *Node) GenesisDoc() *types.GenesisDoc {
  1496. return n.genesisDoc
  1497. }
  1498. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  1499. func (n *Node) ProxyApp() proxy.AppConns {
  1500. return n.proxyApp
  1501. }
  1502. // Config returns the Node's config.
  1503. func (n *Node) Config() *cfg.Config {
  1504. return n.config
  1505. }
  1506. // TxIndexer returns the Node's TxIndexer.
  1507. func (n *Node) TxIndexer() indexer.TxIndexer {
  1508. return n.txIndexer
  1509. }
  1510. //------------------------------------------------------------------------------
  1511. func (n *Node) Listeners() []string {
  1512. return []string{
  1513. fmt.Sprintf("Listener(@%v)", n.config.P2P.ExternalAddress),
  1514. }
  1515. }
  1516. func (n *Node) IsListening() bool {
  1517. return n.isListening
  1518. }
  1519. // NodeInfo returns the Node's Info from the Switch.
  1520. func (n *Node) NodeInfo() p2p.NodeInfo {
  1521. return n.nodeInfo
  1522. }
  1523. func makeNodeInfo(
  1524. config *cfg.Config,
  1525. nodeKey p2p.NodeKey,
  1526. txIndexer indexer.TxIndexer,
  1527. genDoc *types.GenesisDoc,
  1528. state sm.State,
  1529. ) (p2p.NodeInfo, error) {
  1530. txIndexerStatus := "on"
  1531. if _, ok := txIndexer.(*null.TxIndex); ok {
  1532. txIndexerStatus = "off"
  1533. }
  1534. var bcChannel byte
  1535. switch config.FastSync.Version {
  1536. case cfg.BlockchainV0:
  1537. bcChannel = byte(bcv0.BlockchainChannel)
  1538. case cfg.BlockchainV2:
  1539. bcChannel = bcv2.BlockchainChannel
  1540. default:
  1541. return p2p.NodeInfo{}, fmt.Errorf("unknown fastsync version %s", config.FastSync.Version)
  1542. }
  1543. nodeInfo := p2p.NodeInfo{
  1544. ProtocolVersion: p2p.NewProtocolVersion(
  1545. version.P2PProtocol, // global
  1546. state.Version.Consensus.Block,
  1547. state.Version.Consensus.App,
  1548. ),
  1549. NodeID: nodeKey.ID,
  1550. Network: genDoc.ChainID,
  1551. Version: version.TMCoreSemVer,
  1552. Channels: []byte{
  1553. bcChannel,
  1554. byte(cs.StateChannel),
  1555. byte(cs.DataChannel),
  1556. byte(cs.VoteChannel),
  1557. byte(cs.VoteSetBitsChannel),
  1558. byte(mempl.MempoolChannel),
  1559. byte(evidence.EvidenceChannel),
  1560. byte(statesync.SnapshotChannel),
  1561. byte(statesync.ChunkChannel),
  1562. },
  1563. Moniker: config.Moniker,
  1564. Other: p2p.NodeInfoOther{
  1565. TxIndex: txIndexerStatus,
  1566. RPCAddress: config.RPC.ListenAddress,
  1567. },
  1568. }
  1569. if config.P2P.PexReactor {
  1570. nodeInfo.Channels = append(nodeInfo.Channels, pex.PexChannel)
  1571. }
  1572. lAddr := config.P2P.ExternalAddress
  1573. if lAddr == "" {
  1574. lAddr = config.P2P.ListenAddress
  1575. }
  1576. nodeInfo.ListenAddr = lAddr
  1577. err := nodeInfo.Validate()
  1578. return nodeInfo, err
  1579. }
  1580. func makeSeedNodeInfo(
  1581. config *cfg.Config,
  1582. nodeKey p2p.NodeKey,
  1583. genDoc *types.GenesisDoc,
  1584. state sm.State,
  1585. ) (p2p.NodeInfo, error) {
  1586. nodeInfo := p2p.NodeInfo{
  1587. ProtocolVersion: p2p.NewProtocolVersion(
  1588. version.P2PProtocol, // global
  1589. state.Version.Consensus.Block,
  1590. state.Version.Consensus.App,
  1591. ),
  1592. NodeID: nodeKey.ID,
  1593. Network: genDoc.ChainID,
  1594. Version: version.TMCoreSemVer,
  1595. Channels: []byte{},
  1596. Moniker: config.Moniker,
  1597. Other: p2p.NodeInfoOther{
  1598. TxIndex: "off",
  1599. RPCAddress: config.RPC.ListenAddress,
  1600. },
  1601. }
  1602. if config.P2P.PexReactor {
  1603. nodeInfo.Channels = append(nodeInfo.Channels, pex.PexChannel)
  1604. }
  1605. lAddr := config.P2P.ExternalAddress
  1606. if lAddr == "" {
  1607. lAddr = config.P2P.ListenAddress
  1608. }
  1609. nodeInfo.ListenAddr = lAddr
  1610. err := nodeInfo.Validate()
  1611. return nodeInfo, err
  1612. }
  1613. //------------------------------------------------------------------------------
  1614. var (
  1615. genesisDocKey = []byte("genesisDoc")
  1616. )
  1617. // LoadStateFromDBOrGenesisDocProvider attempts to load the state from the
  1618. // database, or creates one using the given genesisDocProvider. On success this also
  1619. // returns the genesis doc loaded through the given provider.
  1620. func LoadStateFromDBOrGenesisDocProvider(
  1621. stateDB dbm.DB,
  1622. genesisDocProvider GenesisDocProvider,
  1623. ) (sm.State, *types.GenesisDoc, error) {
  1624. // Get genesis doc
  1625. genDoc, err := loadGenesisDoc(stateDB)
  1626. if err != nil {
  1627. genDoc, err = genesisDocProvider()
  1628. if err != nil {
  1629. return sm.State{}, nil, err
  1630. }
  1631. err = genDoc.ValidateAndComplete()
  1632. if err != nil {
  1633. return sm.State{}, nil, fmt.Errorf("error in genesis doc: %w", err)
  1634. }
  1635. // save genesis doc to prevent a certain class of user errors (e.g. when it
  1636. // was changed, accidentally or not). Also good for audit trail.
  1637. if err := saveGenesisDoc(stateDB, genDoc); err != nil {
  1638. return sm.State{}, nil, err
  1639. }
  1640. }
  1641. stateStore := sm.NewStore(stateDB)
  1642. state, err := stateStore.LoadFromDBOrGenesisDoc(genDoc)
  1643. if err != nil {
  1644. return sm.State{}, nil, err
  1645. }
  1646. return state, genDoc, nil
  1647. }
  1648. // panics if failed to unmarshal bytes
  1649. func loadGenesisDoc(db dbm.DB) (*types.GenesisDoc, error) {
  1650. b, err := db.Get(genesisDocKey)
  1651. if err != nil {
  1652. panic(err)
  1653. }
  1654. if len(b) == 0 {
  1655. return nil, errors.New("genesis doc not found")
  1656. }
  1657. var genDoc *types.GenesisDoc
  1658. err = tmjson.Unmarshal(b, &genDoc)
  1659. if err != nil {
  1660. panic(fmt.Sprintf("Failed to load genesis doc due to unmarshaling error: %v (bytes: %X)", err, b))
  1661. }
  1662. return genDoc, nil
  1663. }
  1664. // panics if failed to marshal the given genesis document
  1665. func saveGenesisDoc(db dbm.DB, genDoc *types.GenesisDoc) error {
  1666. b, err := tmjson.Marshal(genDoc)
  1667. if err != nil {
  1668. return fmt.Errorf("failed to save genesis doc due to marshaling error: %w", err)
  1669. }
  1670. if err := db.SetSync(genesisDocKey, b); err != nil {
  1671. return err
  1672. }
  1673. return nil
  1674. }
  1675. func createAndStartPrivValidatorSocketClient(
  1676. listenAddr,
  1677. chainID string,
  1678. logger log.Logger,
  1679. ) (types.PrivValidator, error) {
  1680. pve, err := privval.NewSignerListener(listenAddr, logger)
  1681. if err != nil {
  1682. return nil, fmt.Errorf("failed to start private validator: %w", err)
  1683. }
  1684. pvsc, err := privval.NewSignerClient(pve, chainID)
  1685. if err != nil {
  1686. return nil, fmt.Errorf("failed to start private validator: %w", err)
  1687. }
  1688. // try to get a pubkey from private validate first time
  1689. _, err = pvsc.GetPubKey(context.TODO())
  1690. if err != nil {
  1691. return nil, fmt.Errorf("can't get pubkey: %w", err)
  1692. }
  1693. const (
  1694. retries = 50 // 50 * 100ms = 5s total
  1695. timeout = 100 * time.Millisecond
  1696. )
  1697. pvscWithRetries := privval.NewRetrySignerClient(pvsc, retries, timeout)
  1698. return pvscWithRetries, nil
  1699. }
  1700. func createAndStartPrivValidatorGRPCClient(
  1701. config *cfg.Config,
  1702. chainID string,
  1703. logger log.Logger,
  1704. ) (types.PrivValidator, error) {
  1705. pvsc, err := tmgrpc.DialRemoteSigner(config, chainID, logger)
  1706. if err != nil {
  1707. return nil, fmt.Errorf("failed to start private validator: %w", err)
  1708. }
  1709. // try to get a pubkey from private validate first time
  1710. _, err = pvsc.GetPubKey(context.TODO())
  1711. if err != nil {
  1712. return nil, fmt.Errorf("can't get pubkey: %w", err)
  1713. }
  1714. return pvsc, nil
  1715. }
  1716. func getRouterConfig(conf *cfg.Config, proxyApp proxy.AppConns) p2p.RouterOptions {
  1717. opts := p2p.RouterOptions{
  1718. QueueType: conf.P2P.QueueType,
  1719. }
  1720. if conf.P2P.MaxNumInboundPeers > 0 {
  1721. opts.MaxIncomingConnectionAttempts = conf.P2P.MaxIncomingConnectionAttempts
  1722. }
  1723. if conf.FilterPeers && proxyApp != nil {
  1724. opts.FilterPeerByID = func(ctx context.Context, id p2p.NodeID) error {
  1725. res, err := proxyApp.Query().QuerySync(context.Background(), abci.RequestQuery{
  1726. Path: fmt.Sprintf("/p2p/filter/id/%s", id),
  1727. })
  1728. if err != nil {
  1729. return err
  1730. }
  1731. if res.IsErr() {
  1732. return fmt.Errorf("error querying abci app: %v", res)
  1733. }
  1734. return nil
  1735. }
  1736. opts.FilterPeerByIP = func(ctx context.Context, ip net.IP, port uint16) error {
  1737. res, err := proxyApp.Query().QuerySync(ctx, abci.RequestQuery{
  1738. Path: fmt.Sprintf("/p2p/filter/addr/%s", net.JoinHostPort(ip.String(), strconv.Itoa(int(port)))),
  1739. })
  1740. if err != nil {
  1741. return err
  1742. }
  1743. if res.IsErr() {
  1744. return fmt.Errorf("error querying abci app: %v", res)
  1745. }
  1746. return nil
  1747. }
  1748. }
  1749. return opts
  1750. }
  1751. // FIXME: Temporary helper function, shims should be removed.
  1752. func makeChannelsFromShims(
  1753. router *p2p.Router,
  1754. chShims map[p2p.ChannelID]*p2p.ChannelDescriptorShim,
  1755. ) map[p2p.ChannelID]*p2p.Channel {
  1756. channels := map[p2p.ChannelID]*p2p.Channel{}
  1757. for chID, chShim := range chShims {
  1758. ch, err := router.OpenChannel(chID, chShim.MsgType, chShim.Descriptor.RecvBufferCapacity)
  1759. if err != nil {
  1760. panic(fmt.Sprintf("failed to open channel %v: %v", chID, err))
  1761. }
  1762. channels[chID] = ch
  1763. }
  1764. return channels
  1765. }
  1766. func getChannelsFromShim(reactorShim *p2p.ReactorShim) map[p2p.ChannelID]*p2p.Channel {
  1767. channels := map[p2p.ChannelID]*p2p.Channel{}
  1768. for chID := range reactorShim.Channels {
  1769. channels[chID] = reactorShim.GetChannel(chID)
  1770. }
  1771. return channels
  1772. }