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.

1299 lines
39 KiB

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
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
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
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
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
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
node: refactor node.NewNode (#3456) The node.NewNode method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the node.TestCreateProposalBlock test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. See also this gist https://gist.github.com/thanethomson/56e1640d057a26186e38ad678a1d114c for some background work done when starting to refactor here. ## Commits: * [WIP] Refactor node.NewNode to simplify The `node.NewNode` method is pretty complex at the moment, an in order to address issues like #3156, we need to simplify the interface for partial node instantiation. In some places, we don't need to build up a full node (like in the `node.TestCreateProposalBlock` test), but the complexity of such partial instantiation needs to be reduced. This PR aims to eventually make this easier/simpler. * Refactor state loading and genesis doc provider into state package * Refactor for clarity of return parameters * Fix incorrect capitalization of error messages * Simplify extracted functions' names * Document optionally-prefixed functions * Refactor optionallyFastSync for clarity of separation of concerns * Restructure function for early return * Restructure function for early return * Remove dependence on deprecated panic functions * refactor code a bit more plus, expose PEXReactor on node * align logger names * add a changelog entry * align logger names 2 * add a note about PEXReactor returning nil
6 years ago
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. "context"
  4. "errors"
  5. "fmt"
  6. "net"
  7. "net/http"
  8. _ "net/http/pprof" // nolint: gosec // securely exposed on separate, optional port
  9. "strconv"
  10. "time"
  11. _ "github.com/lib/pq" // provide the psql db driver
  12. "github.com/prometheus/client_golang/prometheus"
  13. "github.com/prometheus/client_golang/prometheus/promhttp"
  14. "github.com/rs/cors"
  15. abci "github.com/tendermint/tendermint/abci/types"
  16. cfg "github.com/tendermint/tendermint/config"
  17. "github.com/tendermint/tendermint/crypto"
  18. cs "github.com/tendermint/tendermint/internal/consensus"
  19. "github.com/tendermint/tendermint/internal/evidence"
  20. "github.com/tendermint/tendermint/internal/mempool"
  21. "github.com/tendermint/tendermint/internal/p2p"
  22. "github.com/tendermint/tendermint/internal/p2p/pex"
  23. "github.com/tendermint/tendermint/internal/statesync"
  24. "github.com/tendermint/tendermint/libs/log"
  25. tmnet "github.com/tendermint/tendermint/libs/net"
  26. tmpubsub "github.com/tendermint/tendermint/libs/pubsub"
  27. "github.com/tendermint/tendermint/libs/service"
  28. "github.com/tendermint/tendermint/libs/strings"
  29. tmtime "github.com/tendermint/tendermint/libs/time"
  30. "github.com/tendermint/tendermint/light"
  31. "github.com/tendermint/tendermint/privval"
  32. tmgrpc "github.com/tendermint/tendermint/privval/grpc"
  33. "github.com/tendermint/tendermint/proxy"
  34. rpccore "github.com/tendermint/tendermint/rpc/core"
  35. grpccore "github.com/tendermint/tendermint/rpc/grpc"
  36. rpcserver "github.com/tendermint/tendermint/rpc/jsonrpc/server"
  37. sm "github.com/tendermint/tendermint/state"
  38. "github.com/tendermint/tendermint/state/indexer"
  39. "github.com/tendermint/tendermint/store"
  40. "github.com/tendermint/tendermint/types"
  41. )
  42. // nodeImpl is the highest level interface to a full Tendermint node.
  43. // It includes all configuration information and running services.
  44. type nodeImpl struct {
  45. service.BaseService
  46. // config
  47. config *cfg.Config
  48. genesisDoc *types.GenesisDoc // initial validator set
  49. privValidator types.PrivValidator // local node's validator key
  50. // network
  51. transport *p2p.MConnTransport
  52. sw *p2p.Switch // p2p connections
  53. peerManager *p2p.PeerManager
  54. router *p2p.Router
  55. addrBook pex.AddrBook // known peers
  56. nodeInfo types.NodeInfo
  57. nodeKey types.NodeKey // our node privkey
  58. isListening bool
  59. // services
  60. eventBus *types.EventBus // pub/sub for services
  61. stateStore sm.Store
  62. blockStore *store.BlockStore // store the blockchain to disk
  63. bcReactor service.Service // for fast-syncing
  64. mempoolReactor service.Service // for gossipping transactions
  65. mempool mempool.Mempool
  66. stateSync bool // whether the node should state sync on startup
  67. stateSyncReactor *statesync.Reactor // for hosting and restoring state sync snapshots
  68. consensusState *cs.State // latest consensus state
  69. consensusReactor *cs.Reactor // for participating in the consensus
  70. pexReactor *pex.Reactor // for exchanging peer addresses
  71. pexReactorV2 *pex.ReactorV2 // for exchanging peer addresses
  72. evidenceReactor *evidence.Reactor
  73. evidencePool *evidence.Pool // tracking evidence
  74. proxyApp proxy.AppConns // connection to the application
  75. rpcListeners []net.Listener // rpc servers
  76. eventSinks []indexer.EventSink
  77. indexerService *indexer.Service
  78. prometheusSrv *http.Server
  79. }
  80. // newDefaultNode returns a Tendermint node with default settings for the
  81. // PrivValidator, ClientCreator, GenesisDoc, and DBProvider.
  82. // It implements NodeProvider.
  83. func newDefaultNode(config *cfg.Config, logger log.Logger) (service.Service, error) {
  84. nodeKey, err := types.LoadOrGenNodeKey(config.NodeKeyFile())
  85. if err != nil {
  86. return nil, fmt.Errorf("failed to load or gen node key %s: %w", config.NodeKeyFile(), err)
  87. }
  88. if config.Mode == cfg.ModeSeed {
  89. return makeSeedNode(config,
  90. cfg.DefaultDBProvider,
  91. nodeKey,
  92. defaultGenesisDocProviderFunc(config),
  93. logger,
  94. )
  95. }
  96. var pval *privval.FilePV
  97. if config.Mode == cfg.ModeValidator {
  98. pval, err = privval.LoadOrGenFilePV(config.PrivValidator.KeyFile(), config.PrivValidator.StateFile())
  99. if err != nil {
  100. return nil, err
  101. }
  102. } else {
  103. pval = nil
  104. }
  105. appClient, _ := proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir())
  106. return makeNode(config,
  107. pval,
  108. nodeKey,
  109. appClient,
  110. defaultGenesisDocProviderFunc(config),
  111. cfg.DefaultDBProvider,
  112. logger,
  113. )
  114. }
  115. // makeNode returns a new, ready to go, Tendermint Node.
  116. func makeNode(config *cfg.Config,
  117. privValidator types.PrivValidator,
  118. nodeKey types.NodeKey,
  119. clientCreator proxy.ClientCreator,
  120. genesisDocProvider genesisDocProvider,
  121. dbProvider cfg.DBProvider,
  122. logger log.Logger) (service.Service, error) {
  123. blockStore, stateDB, err := initDBs(config, dbProvider)
  124. if err != nil {
  125. return nil, err
  126. }
  127. stateStore := sm.NewStore(stateDB)
  128. genDoc, err := genesisDocProvider()
  129. if err != nil {
  130. return nil, err
  131. }
  132. err = genDoc.ValidateAndComplete()
  133. if err != nil {
  134. return nil, fmt.Errorf("error in genesis doc: %w", err)
  135. }
  136. state, err := loadStateFromDBOrGenesisDocProvider(stateStore, genDoc)
  137. if err != nil {
  138. return nil, err
  139. }
  140. // Create the proxyApp and establish connections to the ABCI app (consensus, mempool, query).
  141. proxyApp, err := createAndStartProxyAppConns(clientCreator, logger)
  142. if err != nil {
  143. return nil, err
  144. }
  145. // EventBus and IndexerService must be started before the handshake because
  146. // we might need to index the txs of the replayed block as this might not have happened
  147. // when the node stopped last time (i.e. the node stopped after it saved the block
  148. // but before it indexed the txs, or, endblocker panicked)
  149. eventBus, err := createAndStartEventBus(logger)
  150. if err != nil {
  151. return nil, err
  152. }
  153. indexerService, eventSinks, err := createAndStartIndexerService(config, dbProvider, eventBus, logger, genDoc.ChainID)
  154. if err != nil {
  155. return nil, err
  156. }
  157. // If an address is provided, listen on the socket for a connection from an
  158. // external signing process.
  159. if config.PrivValidator.ListenAddr != "" {
  160. protocol, _ := tmnet.ProtocolAndAddress(config.PrivValidator.ListenAddr)
  161. // FIXME: we should start services inside OnStart
  162. switch protocol {
  163. case "grpc":
  164. privValidator, err = createAndStartPrivValidatorGRPCClient(config, genDoc.ChainID, logger)
  165. if err != nil {
  166. return nil, fmt.Errorf("error with private validator grpc client: %w", err)
  167. }
  168. default:
  169. privValidator, err = createAndStartPrivValidatorSocketClient(config.PrivValidator.ListenAddr, genDoc.ChainID, logger)
  170. if err != nil {
  171. return nil, fmt.Errorf("error with private validator socket client: %w", err)
  172. }
  173. }
  174. }
  175. var pubKey crypto.PubKey
  176. if config.Mode == cfg.ModeValidator {
  177. pubKey, err = privValidator.GetPubKey(context.TODO())
  178. if err != nil {
  179. return nil, fmt.Errorf("can't get pubkey: %w", err)
  180. }
  181. if pubKey == nil {
  182. return nil, errors.New("could not retrieve public key from private validator")
  183. }
  184. }
  185. // Determine whether we should attempt state sync.
  186. stateSync := config.StateSync.Enable && !onlyValidatorIsUs(state, pubKey)
  187. if stateSync && state.LastBlockHeight > 0 {
  188. logger.Info("Found local state with non-zero height, skipping state sync")
  189. stateSync = false
  190. }
  191. // Create the handshaker, which calls RequestInfo, sets the AppVersion on the state,
  192. // and replays any blocks as necessary to sync tendermint with the app.
  193. consensusLogger := logger.With("module", "consensus")
  194. if !stateSync {
  195. if err := doHandshake(stateStore, state, blockStore, genDoc, eventBus, proxyApp, consensusLogger); err != nil {
  196. return nil, err
  197. }
  198. // Reload the state. It will have the Version.Consensus.App set by the
  199. // Handshake, and may have other modifications as well (ie. depending on
  200. // what happened during block replay).
  201. state, err = stateStore.Load()
  202. if err != nil {
  203. return nil, fmt.Errorf("cannot load state: %w", err)
  204. }
  205. }
  206. // Determine whether we should do fast sync. This must happen after the handshake, since the
  207. // app may modify the validator set, specifying ourself as the only validator.
  208. fastSync := config.FastSyncMode && !onlyValidatorIsUs(state, pubKey)
  209. logNodeStartupInfo(state, pubKey, logger, consensusLogger, config.Mode)
  210. // TODO: Fetch and provide real options and do proper p2p bootstrapping.
  211. // TODO: Use a persistent peer database.
  212. nodeInfo, err := makeNodeInfo(config, nodeKey, eventSinks, genDoc, state)
  213. if err != nil {
  214. return nil, err
  215. }
  216. p2pLogger := logger.With("module", "p2p")
  217. transport := createTransport(p2pLogger, config)
  218. peerManager, err := createPeerManager(config, dbProvider, p2pLogger, nodeKey.ID)
  219. if err != nil {
  220. return nil, fmt.Errorf("failed to create peer manager: %w", err)
  221. }
  222. csMetrics, p2pMetrics, memplMetrics, smMetrics := defaultMetricsProvider(config.Instrumentation)(genDoc.ChainID)
  223. router, err := createRouter(p2pLogger, p2pMetrics, nodeInfo, nodeKey.PrivKey,
  224. peerManager, transport, getRouterConfig(config, proxyApp))
  225. if err != nil {
  226. return nil, fmt.Errorf("failed to create router: %w", err)
  227. }
  228. mpReactorShim, mpReactor, mp, err := createMempoolReactor(
  229. config, proxyApp, state, memplMetrics, peerManager, router, logger,
  230. )
  231. if err != nil {
  232. return nil, err
  233. }
  234. evReactorShim, evReactor, evPool, err := createEvidenceReactor(
  235. config, dbProvider, stateDB, blockStore, peerManager, router, logger,
  236. )
  237. if err != nil {
  238. return nil, err
  239. }
  240. // make block executor for consensus and blockchain reactors to execute blocks
  241. blockExec := sm.NewBlockExecutor(
  242. stateStore,
  243. logger.With("module", "state"),
  244. proxyApp.Consensus(),
  245. mp,
  246. evPool,
  247. blockStore,
  248. sm.BlockExecutorWithMetrics(smMetrics),
  249. )
  250. csReactorShim, csReactor, csState := createConsensusReactor(
  251. config, state, blockExec, blockStore, mp, evPool,
  252. privValidator, csMetrics, stateSync || fastSync, eventBus,
  253. peerManager, router, consensusLogger,
  254. )
  255. // Create the blockchain reactor. Note, we do not start fast sync if we're
  256. // doing a state sync first.
  257. bcReactorShim, bcReactor, err := createBlockchainReactor(
  258. logger, config, state, blockExec, blockStore, csReactor,
  259. peerManager, router, fastSync && !stateSync, csMetrics,
  260. )
  261. if err != nil {
  262. return nil, fmt.Errorf("could not create blockchain reactor: %w", err)
  263. }
  264. // TODO: Remove this once the switch is removed.
  265. var bcReactorForSwitch p2p.Reactor
  266. if bcReactorShim != nil {
  267. bcReactorForSwitch = bcReactorShim
  268. } else {
  269. bcReactorForSwitch = bcReactor.(p2p.Reactor)
  270. }
  271. // Make ConsensusReactor. Don't enable fully if doing a state sync and/or fast sync first.
  272. // FIXME We need to update metrics here, since other reactors don't have access to them.
  273. if stateSync {
  274. csMetrics.StateSyncing.Set(1)
  275. } else if fastSync {
  276. csMetrics.FastSyncing.Set(1)
  277. }
  278. // Set up state sync reactor, and schedule a sync if requested.
  279. // FIXME The way we do phased startups (e.g. replay -> fast sync -> consensus) is very messy,
  280. // we should clean this whole thing up. See:
  281. // https://github.com/tendermint/tendermint/issues/4644
  282. var (
  283. stateSyncReactor *statesync.Reactor
  284. stateSyncReactorShim *p2p.ReactorShim
  285. channels map[p2p.ChannelID]*p2p.Channel
  286. peerUpdates *p2p.PeerUpdates
  287. )
  288. stateSyncReactorShim = p2p.NewReactorShim(logger.With("module", "statesync"), "StateSyncShim", statesync.ChannelShims)
  289. if config.P2P.DisableLegacy {
  290. channels = makeChannelsFromShims(router, statesync.ChannelShims)
  291. peerUpdates = peerManager.Subscribe()
  292. } else {
  293. channels = getChannelsFromShim(stateSyncReactorShim)
  294. peerUpdates = stateSyncReactorShim.PeerUpdates
  295. }
  296. stateSyncReactor = statesync.NewReactor(
  297. *config.StateSync,
  298. stateSyncReactorShim.Logger,
  299. proxyApp.Snapshot(),
  300. proxyApp.Query(),
  301. channels[statesync.SnapshotChannel],
  302. channels[statesync.ChunkChannel],
  303. channels[statesync.LightBlockChannel],
  304. peerUpdates,
  305. stateStore,
  306. blockStore,
  307. config.StateSync.TempDir,
  308. )
  309. // add the channel descriptors to both the transports
  310. // FIXME: This should be removed when the legacy p2p stack is removed and
  311. // transports can either be agnostic to channel descriptors or can be
  312. // declared in the constructor.
  313. transport.AddChannelDescriptors(mpReactorShim.GetChannels())
  314. transport.AddChannelDescriptors(bcReactorForSwitch.GetChannels())
  315. transport.AddChannelDescriptors(csReactorShim.GetChannels())
  316. transport.AddChannelDescriptors(evReactorShim.GetChannels())
  317. transport.AddChannelDescriptors(stateSyncReactorShim.GetChannels())
  318. // Optionally, start the pex reactor
  319. //
  320. // TODO:
  321. //
  322. // We need to set Seeds and PersistentPeers on the switch,
  323. // since it needs to be able to use these (and their DNS names)
  324. // even if the PEX is off. We can include the DNS name in the NetAddress,
  325. // but it would still be nice to have a clear list of the current "PersistentPeers"
  326. // somewhere that we can return with net_info.
  327. //
  328. // If PEX is on, it should handle dialing the seeds. Otherwise the switch does it.
  329. // Note we currently use the addrBook regardless at least for AddOurAddress
  330. var (
  331. pexReactor *pex.Reactor
  332. pexReactorV2 *pex.ReactorV2
  333. sw *p2p.Switch
  334. addrBook pex.AddrBook
  335. )
  336. pexCh := pex.ChannelDescriptor()
  337. transport.AddChannelDescriptors([]*p2p.ChannelDescriptor{&pexCh})
  338. if config.P2P.PexReactor {
  339. if config.P2P.DisableLegacy {
  340. addrBook = nil
  341. pexReactorV2, err = createPEXReactorV2(config, logger, peerManager, router)
  342. if err != nil {
  343. return nil, err
  344. }
  345. } else {
  346. // setup Transport and Switch
  347. sw = createSwitch(
  348. config, transport, p2pMetrics, mpReactorShim, bcReactorForSwitch,
  349. stateSyncReactorShim, csReactorShim, evReactorShim, proxyApp, nodeInfo, nodeKey, p2pLogger,
  350. )
  351. err = sw.AddPersistentPeers(strings.SplitAndTrimEmpty(config.P2P.PersistentPeers, ",", " "))
  352. if err != nil {
  353. return nil, fmt.Errorf("could not add peers from persistent-peers field: %w", err)
  354. }
  355. err = sw.AddUnconditionalPeerIDs(strings.SplitAndTrimEmpty(config.P2P.UnconditionalPeerIDs, ",", " "))
  356. if err != nil {
  357. return nil, fmt.Errorf("could not add peer ids from unconditional_peer_ids field: %w", err)
  358. }
  359. addrBook, err = createAddrBookAndSetOnSwitch(config, sw, p2pLogger, nodeKey)
  360. if err != nil {
  361. return nil, fmt.Errorf("could not create addrbook: %w", err)
  362. }
  363. pexReactor = createPEXReactorAndAddToSwitch(addrBook, config, sw, logger)
  364. }
  365. }
  366. if config.RPC.PprofListenAddress != "" {
  367. go func() {
  368. logger.Info("Starting pprof server", "laddr", config.RPC.PprofListenAddress)
  369. logger.Error("pprof server error", "err", http.ListenAndServe(config.RPC.PprofListenAddress, nil))
  370. }()
  371. }
  372. node := &nodeImpl{
  373. config: config,
  374. genesisDoc: genDoc,
  375. privValidator: privValidator,
  376. transport: transport,
  377. sw: sw,
  378. peerManager: peerManager,
  379. router: router,
  380. addrBook: addrBook,
  381. nodeInfo: nodeInfo,
  382. nodeKey: nodeKey,
  383. stateStore: stateStore,
  384. blockStore: blockStore,
  385. bcReactor: bcReactor,
  386. mempoolReactor: mpReactor,
  387. mempool: mp,
  388. consensusState: csState,
  389. consensusReactor: csReactor,
  390. stateSyncReactor: stateSyncReactor,
  391. stateSync: stateSync,
  392. pexReactor: pexReactor,
  393. pexReactorV2: pexReactorV2,
  394. evidenceReactor: evReactor,
  395. evidencePool: evPool,
  396. proxyApp: proxyApp,
  397. indexerService: indexerService,
  398. eventBus: eventBus,
  399. eventSinks: eventSinks,
  400. }
  401. node.BaseService = *service.NewBaseService(logger, "Node", node)
  402. return node, nil
  403. }
  404. // makeSeedNode returns a new seed node, containing only p2p, pex reactor
  405. func makeSeedNode(config *cfg.Config,
  406. dbProvider cfg.DBProvider,
  407. nodeKey types.NodeKey,
  408. genesisDocProvider genesisDocProvider,
  409. logger log.Logger,
  410. ) (service.Service, error) {
  411. genDoc, err := genesisDocProvider()
  412. if err != nil {
  413. return nil, err
  414. }
  415. state, err := sm.MakeGenesisState(genDoc)
  416. if err != nil {
  417. return nil, err
  418. }
  419. nodeInfo, err := makeSeedNodeInfo(config, nodeKey, genDoc, state)
  420. if err != nil {
  421. return nil, err
  422. }
  423. // Setup Transport and Switch.
  424. p2pMetrics := p2p.PrometheusMetrics(config.Instrumentation.Namespace, "chain_id", genDoc.ChainID)
  425. p2pLogger := logger.With("module", "p2p")
  426. transport := createTransport(p2pLogger, config)
  427. sw := createSwitch(
  428. config, transport, p2pMetrics, nil, nil,
  429. nil, nil, nil, nil, nodeInfo, nodeKey, p2pLogger,
  430. )
  431. err = sw.AddPersistentPeers(strings.SplitAndTrimEmpty(config.P2P.PersistentPeers, ",", " "))
  432. if err != nil {
  433. return nil, fmt.Errorf("could not add peers from persistent_peers field: %w", err)
  434. }
  435. err = sw.AddUnconditionalPeerIDs(strings.SplitAndTrimEmpty(config.P2P.UnconditionalPeerIDs, ",", " "))
  436. if err != nil {
  437. return nil, fmt.Errorf("could not add peer ids from unconditional_peer_ids field: %w", err)
  438. }
  439. addrBook, err := createAddrBookAndSetOnSwitch(config, sw, p2pLogger, nodeKey)
  440. if err != nil {
  441. return nil, fmt.Errorf("could not create addrbook: %w", err)
  442. }
  443. peerManager, err := createPeerManager(config, dbProvider, p2pLogger, nodeKey.ID)
  444. if err != nil {
  445. return nil, fmt.Errorf("failed to create peer manager: %w", err)
  446. }
  447. router, err := createRouter(p2pLogger, p2pMetrics, nodeInfo, nodeKey.PrivKey,
  448. peerManager, transport, getRouterConfig(config, nil))
  449. if err != nil {
  450. return nil, fmt.Errorf("failed to create router: %w", err)
  451. }
  452. var (
  453. pexReactor *pex.Reactor
  454. pexReactorV2 *pex.ReactorV2
  455. )
  456. // add the pex reactor
  457. // FIXME: we add channel descriptors to both the router and the transport but only the router
  458. // should be aware of channel info. We should remove this from transport once the legacy
  459. // p2p stack is removed.
  460. pexCh := pex.ChannelDescriptor()
  461. transport.AddChannelDescriptors([]*p2p.ChannelDescriptor{&pexCh})
  462. if config.P2P.DisableLegacy {
  463. pexReactorV2, err = createPEXReactorV2(config, logger, peerManager, router)
  464. if err != nil {
  465. return nil, err
  466. }
  467. } else {
  468. pexReactor = createPEXReactorAndAddToSwitch(addrBook, config, sw, logger)
  469. }
  470. if config.RPC.PprofListenAddress != "" {
  471. go func() {
  472. logger.Info("Starting pprof server", "laddr", config.RPC.PprofListenAddress)
  473. logger.Error("pprof server error", "err", http.ListenAndServe(config.RPC.PprofListenAddress, nil))
  474. }()
  475. }
  476. node := &nodeImpl{
  477. config: config,
  478. genesisDoc: genDoc,
  479. transport: transport,
  480. sw: sw,
  481. addrBook: addrBook,
  482. nodeInfo: nodeInfo,
  483. nodeKey: nodeKey,
  484. peerManager: peerManager,
  485. router: router,
  486. pexReactor: pexReactor,
  487. pexReactorV2: pexReactorV2,
  488. }
  489. node.BaseService = *service.NewBaseService(logger, "SeedNode", node)
  490. return node, nil
  491. }
  492. // OnStart starts the Node. It implements service.Service.
  493. func (n *nodeImpl) OnStart() error {
  494. now := tmtime.Now()
  495. genTime := n.genesisDoc.GenesisTime
  496. if genTime.After(now) {
  497. n.Logger.Info("Genesis time is in the future. Sleeping until then...", "genTime", genTime)
  498. time.Sleep(genTime.Sub(now))
  499. }
  500. // Start the RPC server before the P2P server
  501. // so we can eg. receive txs for the first block
  502. if n.config.RPC.ListenAddress != "" && n.config.Mode != cfg.ModeSeed {
  503. listeners, err := n.startRPC()
  504. if err != nil {
  505. return err
  506. }
  507. n.rpcListeners = listeners
  508. }
  509. if n.config.Instrumentation.Prometheus &&
  510. n.config.Instrumentation.PrometheusListenAddr != "" {
  511. n.prometheusSrv = n.startPrometheusServer(n.config.Instrumentation.PrometheusListenAddr)
  512. }
  513. // Start the transport.
  514. addr, err := types.NewNetAddressString(n.nodeKey.ID.AddressString(n.config.P2P.ListenAddress))
  515. if err != nil {
  516. return err
  517. }
  518. if err := n.transport.Listen(p2p.NewEndpoint(addr)); err != nil {
  519. return err
  520. }
  521. n.isListening = true
  522. n.Logger.Info("p2p service", "legacy_enabled", !n.config.P2P.DisableLegacy)
  523. if n.config.P2P.DisableLegacy {
  524. err = n.router.Start()
  525. } else {
  526. // Add private IDs to addrbook to block those peers being added
  527. n.addrBook.AddPrivateIDs(strings.SplitAndTrimEmpty(n.config.P2P.PrivatePeerIDs, ",", " "))
  528. err = n.sw.Start()
  529. }
  530. if err != nil {
  531. return err
  532. }
  533. if n.config.Mode != cfg.ModeSeed {
  534. if n.config.FastSync.Version == cfg.BlockchainV0 {
  535. // Start the real blockchain reactor separately since the switch uses the shim.
  536. if err := n.bcReactor.Start(); err != nil {
  537. return err
  538. }
  539. }
  540. // Start the real consensus reactor separately since the switch uses the shim.
  541. if err := n.consensusReactor.Start(); err != nil {
  542. return err
  543. }
  544. // Start the real state sync reactor separately since the switch uses the shim.
  545. if err := n.stateSyncReactor.Start(); err != nil {
  546. return err
  547. }
  548. // Start the real mempool reactor separately since the switch uses the shim.
  549. if err := n.mempoolReactor.Start(); err != nil {
  550. return err
  551. }
  552. // Start the real evidence reactor separately since the switch uses the shim.
  553. if err := n.evidenceReactor.Start(); err != nil {
  554. return err
  555. }
  556. }
  557. if n.config.P2P.DisableLegacy && n.pexReactorV2 != nil {
  558. if err := n.pexReactorV2.Start(); err != nil {
  559. return err
  560. }
  561. } else {
  562. // Always connect to persistent peers
  563. err = n.sw.DialPeersAsync(strings.SplitAndTrimEmpty(n.config.P2P.PersistentPeers, ",", " "))
  564. if err != nil {
  565. return fmt.Errorf("could not dial peers from persistent-peers field: %w", err)
  566. }
  567. }
  568. // Run state sync
  569. if n.stateSync {
  570. bcR, ok := n.bcReactor.(cs.FastSyncReactor)
  571. if !ok {
  572. return fmt.Errorf("this blockchain reactor does not support switching from state sync")
  573. }
  574. // we need to get the genesis state to get parameters such as
  575. state, err := sm.MakeGenesisState(n.genesisDoc)
  576. if err != nil {
  577. return fmt.Errorf("unable to derive state: %w", err)
  578. }
  579. ssc := n.config.StateSync
  580. sp, err := constructStateProvider(ssc, state, n.Logger.With("module", "light"))
  581. if err != nil {
  582. return fmt.Errorf("failed to set up light client state provider: %w", err)
  583. }
  584. if err := startStateSync(n.stateSyncReactor, bcR, n.consensusReactor, sp,
  585. ssc, n.config.FastSyncMode, state.InitialHeight, n.eventBus); err != nil {
  586. return fmt.Errorf("failed to start state sync: %w", err)
  587. }
  588. }
  589. return nil
  590. }
  591. // OnStop stops the Node. It implements service.Service.
  592. func (n *nodeImpl) OnStop() {
  593. n.Logger.Info("Stopping Node")
  594. // first stop the non-reactor services
  595. if err := n.eventBus.Stop(); err != nil {
  596. n.Logger.Error("Error closing eventBus", "err", err)
  597. }
  598. if err := n.indexerService.Stop(); err != nil {
  599. n.Logger.Error("Error closing indexerService", "err", err)
  600. }
  601. if n.config.Mode != cfg.ModeSeed {
  602. // now stop the reactors
  603. if n.config.FastSync.Version == cfg.BlockchainV0 {
  604. // Stop the real blockchain reactor separately since the switch uses the shim.
  605. if err := n.bcReactor.Stop(); err != nil {
  606. n.Logger.Error("failed to stop the blockchain reactor", "err", err)
  607. }
  608. }
  609. // Stop the real consensus reactor separately since the switch uses the shim.
  610. if err := n.consensusReactor.Stop(); err != nil {
  611. n.Logger.Error("failed to stop the consensus reactor", "err", err)
  612. }
  613. // Stop the real state sync reactor separately since the switch uses the shim.
  614. if err := n.stateSyncReactor.Stop(); err != nil {
  615. n.Logger.Error("failed to stop the state sync reactor", "err", err)
  616. }
  617. // Stop the real mempool reactor separately since the switch uses the shim.
  618. if err := n.mempoolReactor.Stop(); err != nil {
  619. n.Logger.Error("failed to stop the mempool reactor", "err", err)
  620. }
  621. // Stop the real evidence reactor separately since the switch uses the shim.
  622. if err := n.evidenceReactor.Stop(); err != nil {
  623. n.Logger.Error("failed to stop the evidence reactor", "err", err)
  624. }
  625. }
  626. if n.config.P2P.DisableLegacy && n.pexReactorV2 != nil {
  627. if err := n.pexReactorV2.Stop(); err != nil {
  628. n.Logger.Error("failed to stop the PEX v2 reactor", "err", err)
  629. }
  630. }
  631. if n.config.P2P.DisableLegacy {
  632. if err := n.router.Stop(); err != nil {
  633. n.Logger.Error("failed to stop router", "err", err)
  634. }
  635. } else {
  636. if err := n.sw.Stop(); err != nil {
  637. n.Logger.Error("failed to stop switch", "err", err)
  638. }
  639. }
  640. if err := n.transport.Close(); err != nil {
  641. n.Logger.Error("Error closing transport", "err", err)
  642. }
  643. n.isListening = false
  644. // finally stop the listeners / external services
  645. for _, l := range n.rpcListeners {
  646. n.Logger.Info("Closing rpc listener", "listener", l)
  647. if err := l.Close(); err != nil {
  648. n.Logger.Error("Error closing listener", "listener", l, "err", err)
  649. }
  650. }
  651. if pvsc, ok := n.privValidator.(service.Service); ok {
  652. if err := pvsc.Stop(); err != nil {
  653. n.Logger.Error("Error closing private validator", "err", err)
  654. }
  655. }
  656. if n.prometheusSrv != nil {
  657. if err := n.prometheusSrv.Shutdown(context.Background()); err != nil {
  658. // Error from closing listeners, or context timeout:
  659. n.Logger.Error("Prometheus HTTP server Shutdown", "err", err)
  660. }
  661. }
  662. }
  663. // ConfigureRPC makes sure RPC has all the objects it needs to operate.
  664. func (n *nodeImpl) ConfigureRPC() (*rpccore.Environment, error) {
  665. rpcCoreEnv := rpccore.Environment{
  666. ProxyAppQuery: n.proxyApp.Query(),
  667. ProxyAppMempool: n.proxyApp.Mempool(),
  668. StateStore: n.stateStore,
  669. BlockStore: n.blockStore,
  670. EvidencePool: n.evidencePool,
  671. ConsensusState: n.consensusState,
  672. P2PPeers: n.sw,
  673. P2PTransport: n,
  674. GenDoc: n.genesisDoc,
  675. EventSinks: n.eventSinks,
  676. ConsensusReactor: n.consensusReactor,
  677. EventBus: n.eventBus,
  678. Mempool: n.mempool,
  679. Logger: n.Logger.With("module", "rpc"),
  680. Config: *n.config.RPC,
  681. FastSyncReactor: n.bcReactor.(cs.FastSyncReactor),
  682. }
  683. if n.config.Mode == cfg.ModeValidator {
  684. pubKey, err := n.privValidator.GetPubKey(context.TODO())
  685. if pubKey == nil || err != nil {
  686. return nil, fmt.Errorf("can't get pubkey: %w", err)
  687. }
  688. rpcCoreEnv.PubKey = pubKey
  689. }
  690. if err := rpcCoreEnv.InitGenesisChunks(); err != nil {
  691. return nil, err
  692. }
  693. return &rpcCoreEnv, nil
  694. }
  695. func (n *nodeImpl) startRPC() ([]net.Listener, error) {
  696. env, err := n.ConfigureRPC()
  697. if err != nil {
  698. return nil, err
  699. }
  700. listenAddrs := strings.SplitAndTrimEmpty(n.config.RPC.ListenAddress, ",", " ")
  701. routes := env.GetRoutes()
  702. if n.config.RPC.Unsafe {
  703. env.AddUnsafe(routes)
  704. }
  705. config := rpcserver.DefaultConfig()
  706. config.MaxBodyBytes = n.config.RPC.MaxBodyBytes
  707. config.MaxHeaderBytes = n.config.RPC.MaxHeaderBytes
  708. config.MaxOpenConnections = n.config.RPC.MaxOpenConnections
  709. // If necessary adjust global WriteTimeout to ensure it's greater than
  710. // TimeoutBroadcastTxCommit.
  711. // See https://github.com/tendermint/tendermint/issues/3435
  712. if config.WriteTimeout <= n.config.RPC.TimeoutBroadcastTxCommit {
  713. config.WriteTimeout = n.config.RPC.TimeoutBroadcastTxCommit + 1*time.Second
  714. }
  715. // we may expose the rpc over both a unix and tcp socket
  716. listeners := make([]net.Listener, len(listenAddrs))
  717. for i, listenAddr := range listenAddrs {
  718. mux := http.NewServeMux()
  719. rpcLogger := n.Logger.With("module", "rpc-server")
  720. wmLogger := rpcLogger.With("protocol", "websocket")
  721. wm := rpcserver.NewWebsocketManager(routes,
  722. rpcserver.OnDisconnect(func(remoteAddr string) {
  723. err := n.eventBus.UnsubscribeAll(context.Background(), remoteAddr)
  724. if err != nil && err != tmpubsub.ErrSubscriptionNotFound {
  725. wmLogger.Error("Failed to unsubscribe addr from events", "addr", remoteAddr, "err", err)
  726. }
  727. }),
  728. rpcserver.ReadLimit(config.MaxBodyBytes),
  729. )
  730. wm.SetLogger(wmLogger)
  731. mux.HandleFunc("/websocket", wm.WebsocketHandler)
  732. rpcserver.RegisterRPCFuncs(mux, routes, rpcLogger)
  733. listener, err := rpcserver.Listen(
  734. listenAddr,
  735. config,
  736. )
  737. if err != nil {
  738. return nil, err
  739. }
  740. var rootHandler http.Handler = mux
  741. if n.config.RPC.IsCorsEnabled() {
  742. corsMiddleware := cors.New(cors.Options{
  743. AllowedOrigins: n.config.RPC.CORSAllowedOrigins,
  744. AllowedMethods: n.config.RPC.CORSAllowedMethods,
  745. AllowedHeaders: n.config.RPC.CORSAllowedHeaders,
  746. })
  747. rootHandler = corsMiddleware.Handler(mux)
  748. }
  749. if n.config.RPC.IsTLSEnabled() {
  750. go func() {
  751. if err := rpcserver.ServeTLS(
  752. listener,
  753. rootHandler,
  754. n.config.RPC.CertFile(),
  755. n.config.RPC.KeyFile(),
  756. rpcLogger,
  757. config,
  758. ); err != nil {
  759. n.Logger.Error("Error serving server with TLS", "err", err)
  760. }
  761. }()
  762. } else {
  763. go func() {
  764. if err := rpcserver.Serve(
  765. listener,
  766. rootHandler,
  767. rpcLogger,
  768. config,
  769. ); err != nil {
  770. n.Logger.Error("Error serving server", "err", err)
  771. }
  772. }()
  773. }
  774. listeners[i] = listener
  775. }
  776. // we expose a simplified api over grpc for convenience to app devs
  777. grpcListenAddr := n.config.RPC.GRPCListenAddress
  778. if grpcListenAddr != "" {
  779. config := rpcserver.DefaultConfig()
  780. config.MaxBodyBytes = n.config.RPC.MaxBodyBytes
  781. config.MaxHeaderBytes = n.config.RPC.MaxHeaderBytes
  782. // NOTE: GRPCMaxOpenConnections is used, not MaxOpenConnections
  783. config.MaxOpenConnections = n.config.RPC.GRPCMaxOpenConnections
  784. // If necessary adjust global WriteTimeout to ensure it's greater than
  785. // TimeoutBroadcastTxCommit.
  786. // See https://github.com/tendermint/tendermint/issues/3435
  787. if config.WriteTimeout <= n.config.RPC.TimeoutBroadcastTxCommit {
  788. config.WriteTimeout = n.config.RPC.TimeoutBroadcastTxCommit + 1*time.Second
  789. }
  790. listener, err := rpcserver.Listen(grpcListenAddr, config)
  791. if err != nil {
  792. return nil, err
  793. }
  794. go func() {
  795. if err := grpccore.StartGRPCServer(env, listener); err != nil {
  796. n.Logger.Error("Error starting gRPC server", "err", err)
  797. }
  798. }()
  799. listeners = append(listeners, listener)
  800. }
  801. return listeners, nil
  802. }
  803. // startPrometheusServer starts a Prometheus HTTP server, listening for metrics
  804. // collectors on addr.
  805. func (n *nodeImpl) startPrometheusServer(addr string) *http.Server {
  806. srv := &http.Server{
  807. Addr: addr,
  808. Handler: promhttp.InstrumentMetricHandler(
  809. prometheus.DefaultRegisterer, promhttp.HandlerFor(
  810. prometheus.DefaultGatherer,
  811. promhttp.HandlerOpts{MaxRequestsInFlight: n.config.Instrumentation.MaxOpenConnections},
  812. ),
  813. ),
  814. }
  815. go func() {
  816. if err := srv.ListenAndServe(); err != http.ErrServerClosed {
  817. // Error starting or closing listener:
  818. n.Logger.Error("Prometheus HTTP server ListenAndServe", "err", err)
  819. }
  820. }()
  821. return srv
  822. }
  823. // Switch returns the Node's Switch.
  824. func (n *nodeImpl) Switch() *p2p.Switch {
  825. return n.sw
  826. }
  827. // BlockStore returns the Node's BlockStore.
  828. func (n *nodeImpl) BlockStore() *store.BlockStore {
  829. return n.blockStore
  830. }
  831. // ConsensusState returns the Node's ConsensusState.
  832. func (n *nodeImpl) ConsensusState() *cs.State {
  833. return n.consensusState
  834. }
  835. // ConsensusReactor returns the Node's ConsensusReactor.
  836. func (n *nodeImpl) ConsensusReactor() *cs.Reactor {
  837. return n.consensusReactor
  838. }
  839. // MempoolReactor returns the Node's mempool reactor.
  840. func (n *nodeImpl) MempoolReactor() service.Service {
  841. return n.mempoolReactor
  842. }
  843. // Mempool returns the Node's mempool.
  844. func (n *nodeImpl) Mempool() mempool.Mempool {
  845. return n.mempool
  846. }
  847. // PEXReactor returns the Node's PEXReactor. It returns nil if PEX is disabled.
  848. func (n *nodeImpl) PEXReactor() *pex.Reactor {
  849. return n.pexReactor
  850. }
  851. // EvidencePool returns the Node's EvidencePool.
  852. func (n *nodeImpl) EvidencePool() *evidence.Pool {
  853. return n.evidencePool
  854. }
  855. // EventBus returns the Node's EventBus.
  856. func (n *nodeImpl) EventBus() *types.EventBus {
  857. return n.eventBus
  858. }
  859. // PrivValidator returns the Node's PrivValidator.
  860. // XXX: for convenience only!
  861. func (n *nodeImpl) PrivValidator() types.PrivValidator {
  862. return n.privValidator
  863. }
  864. // GenesisDoc returns the Node's GenesisDoc.
  865. func (n *nodeImpl) GenesisDoc() *types.GenesisDoc {
  866. return n.genesisDoc
  867. }
  868. // ProxyApp returns the Node's AppConns, representing its connections to the ABCI application.
  869. func (n *nodeImpl) ProxyApp() proxy.AppConns {
  870. return n.proxyApp
  871. }
  872. // Config returns the Node's config.
  873. func (n *nodeImpl) Config() *cfg.Config {
  874. return n.config
  875. }
  876. // EventSinks returns the Node's event indexing sinks.
  877. func (n *nodeImpl) EventSinks() []indexer.EventSink {
  878. return n.eventSinks
  879. }
  880. //------------------------------------------------------------------------------
  881. func (n *nodeImpl) Listeners() []string {
  882. return []string{
  883. fmt.Sprintf("Listener(@%v)", n.config.P2P.ExternalAddress),
  884. }
  885. }
  886. func (n *nodeImpl) IsListening() bool {
  887. return n.isListening
  888. }
  889. // NodeInfo returns the Node's Info from the Switch.
  890. func (n *nodeImpl) NodeInfo() types.NodeInfo {
  891. return n.nodeInfo
  892. }
  893. // startStateSync starts an asynchronous state sync process, then switches to fast sync mode.
  894. func startStateSync(
  895. ssR statesync.SyncReactor,
  896. bcR cs.FastSyncReactor,
  897. conR cs.ConsSyncReactor,
  898. sp statesync.StateProvider,
  899. config *cfg.StateSyncConfig,
  900. fastSync bool,
  901. stateInitHeight int64,
  902. eb *types.EventBus,
  903. ) error {
  904. stateSyncLogger := eb.Logger.With("module", "statesync")
  905. stateSyncLogger.Info("starting state sync...")
  906. // at the beginning of the statesync start, we use the initialHeight as the event height
  907. // because of the statesync doesn't have the concreate state height before fetched the snapshot.
  908. d := types.EventDataStateSyncStatus{Complete: false, Height: stateInitHeight}
  909. if err := eb.PublishEventStateSyncStatus(d); err != nil {
  910. stateSyncLogger.Error("failed to emit the statesync start event", "err", err)
  911. }
  912. go func() {
  913. state, err := ssR.Sync(context.TODO(), sp, config.DiscoveryTime)
  914. if err != nil {
  915. stateSyncLogger.Error("state sync failed", "err", err)
  916. return
  917. }
  918. if err := ssR.Backfill(state); err != nil {
  919. stateSyncLogger.Error("backfill failed; node has insufficient history to verify all evidence;"+
  920. " proceeding optimistically...", "err", err)
  921. }
  922. conR.SetStateSyncingMetrics(0)
  923. d := types.EventDataStateSyncStatus{Complete: true, Height: state.LastBlockHeight}
  924. if err := eb.PublishEventStateSyncStatus(d); err != nil {
  925. stateSyncLogger.Error("failed to emit the statesync start event", "err", err)
  926. }
  927. if fastSync {
  928. // FIXME Very ugly to have these metrics bleed through here.
  929. conR.SetFastSyncingMetrics(1)
  930. if err := bcR.SwitchToFastSync(state); err != nil {
  931. stateSyncLogger.Error("failed to switch to fast sync", "err", err)
  932. return
  933. }
  934. d := types.EventDataFastSyncStatus{Complete: false, Height: state.LastBlockHeight}
  935. if err := eb.PublishEventFastSyncStatus(d); err != nil {
  936. stateSyncLogger.Error("failed to emit the fastsync starting event", "err", err)
  937. }
  938. } else {
  939. conR.SwitchToConsensus(state, true)
  940. }
  941. }()
  942. return nil
  943. }
  944. // genesisDocProvider returns a GenesisDoc.
  945. // It allows the GenesisDoc to be pulled from sources other than the
  946. // filesystem, for instance from a distributed key-value store cluster.
  947. type genesisDocProvider func() (*types.GenesisDoc, error)
  948. // defaultGenesisDocProviderFunc returns a GenesisDocProvider that loads
  949. // the GenesisDoc from the config.GenesisFile() on the filesystem.
  950. func defaultGenesisDocProviderFunc(config *cfg.Config) genesisDocProvider {
  951. return func() (*types.GenesisDoc, error) {
  952. return types.GenesisDocFromFile(config.GenesisFile())
  953. }
  954. }
  955. // metricsProvider returns a consensus, p2p and mempool Metrics.
  956. type metricsProvider func(chainID string) (*cs.Metrics, *p2p.Metrics, *mempool.Metrics, *sm.Metrics)
  957. // defaultMetricsProvider returns Metrics build using Prometheus client library
  958. // if Prometheus is enabled. Otherwise, it returns no-op Metrics.
  959. func defaultMetricsProvider(config *cfg.InstrumentationConfig) metricsProvider {
  960. return func(chainID string) (*cs.Metrics, *p2p.Metrics, *mempool.Metrics, *sm.Metrics) {
  961. if config.Prometheus {
  962. return cs.PrometheusMetrics(config.Namespace, "chain_id", chainID),
  963. p2p.PrometheusMetrics(config.Namespace, "chain_id", chainID),
  964. mempool.PrometheusMetrics(config.Namespace, "chain_id", chainID),
  965. sm.PrometheusMetrics(config.Namespace, "chain_id", chainID)
  966. }
  967. return cs.NopMetrics(), p2p.NopMetrics(), mempool.NopMetrics(), sm.NopMetrics()
  968. }
  969. }
  970. //------------------------------------------------------------------------------
  971. // loadStateFromDBOrGenesisDocProvider attempts to load the state from the
  972. // database, or creates one using the given genesisDocProvider. On success this also
  973. // returns the genesis doc loaded through the given provider.
  974. func loadStateFromDBOrGenesisDocProvider(
  975. stateStore sm.Store,
  976. genDoc *types.GenesisDoc,
  977. ) (sm.State, error) {
  978. // 1. Attempt to load state form the database
  979. state, err := stateStore.Load()
  980. if err != nil {
  981. return sm.State{}, err
  982. }
  983. if state.IsEmpty() {
  984. // 2. If it's not there, derive it from the genesis doc
  985. state, err = sm.MakeGenesisState(genDoc)
  986. if err != nil {
  987. return sm.State{}, err
  988. }
  989. }
  990. return state, nil
  991. }
  992. func createAndStartPrivValidatorSocketClient(
  993. listenAddr,
  994. chainID string,
  995. logger log.Logger,
  996. ) (types.PrivValidator, error) {
  997. pve, err := privval.NewSignerListener(listenAddr, logger)
  998. if err != nil {
  999. return nil, fmt.Errorf("failed to start private validator: %w", err)
  1000. }
  1001. pvsc, err := privval.NewSignerClient(pve, chainID)
  1002. if err != nil {
  1003. return nil, fmt.Errorf("failed to start private validator: %w", err)
  1004. }
  1005. // try to get a pubkey from private validate first time
  1006. _, err = pvsc.GetPubKey(context.TODO())
  1007. if err != nil {
  1008. return nil, fmt.Errorf("can't get pubkey: %w", err)
  1009. }
  1010. const (
  1011. retries = 50 // 50 * 100ms = 5s total
  1012. timeout = 100 * time.Millisecond
  1013. )
  1014. pvscWithRetries := privval.NewRetrySignerClient(pvsc, retries, timeout)
  1015. return pvscWithRetries, nil
  1016. }
  1017. func createAndStartPrivValidatorGRPCClient(
  1018. config *cfg.Config,
  1019. chainID string,
  1020. logger log.Logger,
  1021. ) (types.PrivValidator, error) {
  1022. pvsc, err := tmgrpc.DialRemoteSigner(
  1023. config.PrivValidator,
  1024. chainID,
  1025. logger,
  1026. config.Instrumentation.Prometheus,
  1027. )
  1028. if err != nil {
  1029. return nil, fmt.Errorf("failed to start private validator: %w", err)
  1030. }
  1031. // try to get a pubkey from private validate first time
  1032. _, err = pvsc.GetPubKey(context.TODO())
  1033. if err != nil {
  1034. return nil, fmt.Errorf("can't get pubkey: %w", err)
  1035. }
  1036. return pvsc, nil
  1037. }
  1038. func getRouterConfig(conf *cfg.Config, proxyApp proxy.AppConns) p2p.RouterOptions {
  1039. opts := p2p.RouterOptions{
  1040. QueueType: conf.P2P.QueueType,
  1041. }
  1042. if conf.P2P.MaxNumInboundPeers > 0 {
  1043. opts.MaxIncomingConnectionAttempts = conf.P2P.MaxIncomingConnectionAttempts
  1044. }
  1045. if conf.FilterPeers && proxyApp != nil {
  1046. opts.FilterPeerByID = func(ctx context.Context, id types.NodeID) error {
  1047. res, err := proxyApp.Query().QuerySync(context.Background(), abci.RequestQuery{
  1048. Path: fmt.Sprintf("/p2p/filter/id/%s", id),
  1049. })
  1050. if err != nil {
  1051. return err
  1052. }
  1053. if res.IsErr() {
  1054. return fmt.Errorf("error querying abci app: %v", res)
  1055. }
  1056. return nil
  1057. }
  1058. opts.FilterPeerByIP = func(ctx context.Context, ip net.IP, port uint16) error {
  1059. res, err := proxyApp.Query().QuerySync(ctx, abci.RequestQuery{
  1060. Path: fmt.Sprintf("/p2p/filter/addr/%s", net.JoinHostPort(ip.String(), strconv.Itoa(int(port)))),
  1061. })
  1062. if err != nil {
  1063. return err
  1064. }
  1065. if res.IsErr() {
  1066. return fmt.Errorf("error querying abci app: %v", res)
  1067. }
  1068. return nil
  1069. }
  1070. }
  1071. return opts
  1072. }
  1073. // FIXME: Temporary helper function, shims should be removed.
  1074. func makeChannelsFromShims(
  1075. router *p2p.Router,
  1076. chShims map[p2p.ChannelID]*p2p.ChannelDescriptorShim,
  1077. ) map[p2p.ChannelID]*p2p.Channel {
  1078. channels := map[p2p.ChannelID]*p2p.Channel{}
  1079. for chID, chShim := range chShims {
  1080. ch, err := router.OpenChannel(*chShim.Descriptor, chShim.MsgType, chShim.Descriptor.RecvBufferCapacity)
  1081. if err != nil {
  1082. panic(fmt.Sprintf("failed to open channel %v: %v", chID, err))
  1083. }
  1084. channels[chID] = ch
  1085. }
  1086. return channels
  1087. }
  1088. func getChannelsFromShim(reactorShim *p2p.ReactorShim) map[p2p.ChannelID]*p2p.Channel {
  1089. channels := map[p2p.ChannelID]*p2p.Channel{}
  1090. for chID := range reactorShim.Channels {
  1091. channels[chID] = reactorShim.GetChannel(chID)
  1092. }
  1093. return channels
  1094. }
  1095. func constructStateProvider(
  1096. ssc *cfg.StateSyncConfig,
  1097. state sm.State,
  1098. logger log.Logger,
  1099. ) (statesync.StateProvider, error) {
  1100. ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second)
  1101. defer cancel()
  1102. to := light.TrustOptions{
  1103. Period: ssc.TrustPeriod,
  1104. Height: ssc.TrustHeight,
  1105. Hash: ssc.TrustHashBytes(),
  1106. }
  1107. return statesync.NewLightClientStateProvider(
  1108. ctx,
  1109. state.ChainID, state.Version, state.InitialHeight,
  1110. ssc.RPCServers, to, logger,
  1111. )
  1112. }