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.

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