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.

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