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.

659 lines
19 KiB

7 years ago
7 years ago
pubsub 2.0 (#3227) * green pubsub tests :OK: * get rid of clientToQueryMap * Subscribe and SubscribeUnbuffered * start adapting other pkgs to new pubsub * nope * rename MsgAndTags to Message * remove TagMap it does not bring any additional benefits * bring back EventSubscriber * fix test * fix data race in TestStartNextHeightCorrectly ``` Write at 0x00c0001c7418 by goroutine 796: github.com/tendermint/tendermint/consensus.TestStartNextHeightCorrectly() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:1296 +0xad testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Previous read at 0x00c0001c7418 by goroutine 858: github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1631 +0x1366 github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1476 +0x8f github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /go/src/github.com/tendermint/tendermint/consensus/state.go:667 +0xa1e github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:628 +0x794 Goroutine 796 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 testing.runTests.func1() /usr/local/go/src/testing/testing.go:1119 +0xa8 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 testing.runTests() /usr/local/go/src/testing/testing.go:1117 +0x4ee testing.(*M).Run() /usr/local/go/src/testing/testing.go:1034 +0x2ee main.main() _testmain.go:214 +0x332 Goroutine 858 (running) created at: github.com/tendermint/tendermint/consensus.(*ConsensusState).startRoutines() /go/src/github.com/tendermint/tendermint/consensus/state.go:334 +0x221 github.com/tendermint/tendermint/consensus.startTestRound() /go/src/github.com/tendermint/tendermint/consensus/common_test.go:122 +0x63 github.com/tendermint/tendermint/consensus.TestStateFullRound1() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:255 +0x397 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ``` * fixes after my own review * fix formatting * wait 100ms before kicking a subscriber out + a test for indexer_service * fixes after my second review * no timeout * add changelog entries * fix merge conflicts * fix typos after Thane's review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * reformat code * rewrite indexer service in the attempt to fix failing test https://github.com/tendermint/tendermint/pull/3227/#issuecomment-462316527 * Revert "rewrite indexer service in the attempt to fix failing test" This reverts commit 0d9107a098230de7138abb1c201877c246e89ed1. * another attempt to fix indexer * fixes after Ethan's review * use unbuffered channel when indexing transactions Refs https://github.com/tendermint/tendermint/pull/3227#discussion_r258786716 * add a comment for EventBus#SubscribeUnbuffered * format code
5 years ago
pubsub 2.0 (#3227) * green pubsub tests :OK: * get rid of clientToQueryMap * Subscribe and SubscribeUnbuffered * start adapting other pkgs to new pubsub * nope * rename MsgAndTags to Message * remove TagMap it does not bring any additional benefits * bring back EventSubscriber * fix test * fix data race in TestStartNextHeightCorrectly ``` Write at 0x00c0001c7418 by goroutine 796: github.com/tendermint/tendermint/consensus.TestStartNextHeightCorrectly() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:1296 +0xad testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 Previous read at 0x00c0001c7418 by goroutine 858: github.com/tendermint/tendermint/consensus.(*ConsensusState).addVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1631 +0x1366 github.com/tendermint/tendermint/consensus.(*ConsensusState).tryAddVote() /go/src/github.com/tendermint/tendermint/consensus/state.go:1476 +0x8f github.com/tendermint/tendermint/consensus.(*ConsensusState).handleMsg() /go/src/github.com/tendermint/tendermint/consensus/state.go:667 +0xa1e github.com/tendermint/tendermint/consensus.(*ConsensusState).receiveRoutine() /go/src/github.com/tendermint/tendermint/consensus/state.go:628 +0x794 Goroutine 796 (running) created at: testing.(*T).Run() /usr/local/go/src/testing/testing.go:878 +0x659 testing.runTests.func1() /usr/local/go/src/testing/testing.go:1119 +0xa8 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 testing.runTests() /usr/local/go/src/testing/testing.go:1117 +0x4ee testing.(*M).Run() /usr/local/go/src/testing/testing.go:1034 +0x2ee main.main() _testmain.go:214 +0x332 Goroutine 858 (running) created at: github.com/tendermint/tendermint/consensus.(*ConsensusState).startRoutines() /go/src/github.com/tendermint/tendermint/consensus/state.go:334 +0x221 github.com/tendermint/tendermint/consensus.startTestRound() /go/src/github.com/tendermint/tendermint/consensus/common_test.go:122 +0x63 github.com/tendermint/tendermint/consensus.TestStateFullRound1() /go/src/github.com/tendermint/tendermint/consensus/state_test.go:255 +0x397 testing.tRunner() /usr/local/go/src/testing/testing.go:827 +0x162 ``` * fixes after my own review * fix formatting * wait 100ms before kicking a subscriber out + a test for indexer_service * fixes after my second review * no timeout * add changelog entries * fix merge conflicts * fix typos after Thane's review Co-Authored-By: melekes <anton.kalyaev@gmail.com> * reformat code * rewrite indexer service in the attempt to fix failing test https://github.com/tendermint/tendermint/pull/3227/#issuecomment-462316527 * Revert "rewrite indexer service in the attempt to fix failing test" This reverts commit 0d9107a098230de7138abb1c201877c246e89ed1. * another attempt to fix indexer * fixes after Ethan's review * use unbuffered channel when indexing transactions Refs https://github.com/tendermint/tendermint/pull/3227#discussion_r258786716 * add a comment for EventBus#SubscribeUnbuffered * format code
5 years ago
6 years ago
fix non deterministic test failures and race in privval socket (#3258) * node: decrease retry conn timeout in test Should fix #3256 The retry timeout was set to the default, which is the same as the accept timeout, so it's no wonder this would fail. Here we decrease the retry timeout so we can try many times before the accept timeout. * p2p: increase handshake timeout in test This fails sometimes, presumably because the handshake timeout is so low (only 50ms). So increase it to 1s. Should fix #3187 * privval: fix race with ping. closes #3237 Pings happen in a go-routine and can happen concurrently with other messages. Since we use a request/response protocol, we expect to send a request and get back the corresponding response. But with pings happening concurrently, this assumption could be violated. We were using a mutex, but only a RWMutex, where the RLock was being held for sending messages - this was to allow the underlying connection to be replaced if it fails. Turns out we actually need to use a full lock (not just a read lock) to prevent multiple requests from happening concurrently. * node: fix test name. DelayedStop -> DelayedStart * autofile: Wait() method In the TestWALTruncate in consensus/wal_test.go we remove the WAL directory at the end of the test. However the wal.Stop() does not properly wait for the autofile group to finish shutting down. Hence it was possible that the group's go-routine is still running when the cleanup happens, which causes a panic since the directory disappeared. Here we add a Wait() method to properly wait until the go-routine exits so we can safely clean up. This fixes #2852.
5 years ago
fix non deterministic test failures and race in privval socket (#3258) * node: decrease retry conn timeout in test Should fix #3256 The retry timeout was set to the default, which is the same as the accept timeout, so it's no wonder this would fail. Here we decrease the retry timeout so we can try many times before the accept timeout. * p2p: increase handshake timeout in test This fails sometimes, presumably because the handshake timeout is so low (only 50ms). So increase it to 1s. Should fix #3187 * privval: fix race with ping. closes #3237 Pings happen in a go-routine and can happen concurrently with other messages. Since we use a request/response protocol, we expect to send a request and get back the corresponding response. But with pings happening concurrently, this assumption could be violated. We were using a mutex, but only a RWMutex, where the RLock was being held for sending messages - this was to allow the underlying connection to be replaced if it fails. Turns out we actually need to use a full lock (not just a read lock) to prevent multiple requests from happening concurrently. * node: fix test name. DelayedStop -> DelayedStart * autofile: Wait() method In the TestWALTruncate in consensus/wal_test.go we remove the WAL directory at the end of the test. However the wal.Stop() does not properly wait for the autofile group to finish shutting down. Hence it was possible that the group's go-routine is still running when the cleanup happens, which causes a panic since the directory disappeared. Here we add a Wait() method to properly wait until the go-routine exits so we can safely clean up. This fixes #2852.
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
5 years ago
privval: refactor Remote signers (#3370) This PR is related to #3107 and a continuation of #3351 It is important to emphasise that in the privval original design, client/server and listening/dialing roles are inverted and do not follow a conventional interaction. Given two hosts A and B: Host A is listener/client Host B is dialer/server (contains the secret key) When A requires a signature, it needs to wait for B to dial in before it can issue a request. A only accepts a single connection and any failure leads to dropping the connection and waiting for B to reconnect. The original rationale behind this design was based on security. Host B only allows outbound connections to a list of whitelisted hosts. It is not possible to reach B unless B dials in. There are no listening/open ports in B. This PR results in the following changes: Refactors ping/heartbeat to avoid previously existing race conditions. Separates transport (dialer/listener) from signing (client/server) concerns to simplify workflow. Unifies and abstracts away the differences between unix and tcp sockets. A single signer endpoint implementation unifies connection handling code (read/write/close/connection obj) The signer request handler (server side) is customizable to increase testability. Updates and extends unit tests A high level overview of the classes is as follows: Transport (endpoints): The following classes take care of establishing a connection SignerDialerEndpoint SignerListeningEndpoint SignerEndpoint groups common functionality (read/write/timeouts/etc.) Signing (client/server): The following classes take care of exchanging request/responses SignerClient SignerServer This PR also closes #3601 Commits: * refactoring - work in progress * reworking unit tests * Encapsulating and fixing unit tests * Improve tests * Clean up * Fix/improve unit tests * clean up tests * Improving service endpoint * fixing unit test * fix linter issues * avoid invalid cache values (improve later?) * complete implementation * wip * improved connection loop * Improve reconnections + fixing unit tests * addressing comments * small formatting changes * clean up * Update node/node.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * check during initialization * dropping connecting when writing fails * removing break * use t.log instead * unifying and using cmn.GetFreePort() * review fixes * reordering and unifying drop connection * closing instead of signalling * refactored service loop * removed superfluous brackets * GetPubKey can return errors * Revert "GetPubKey can return errors" This reverts commit 68c06f19b4650389d7e5ab1659b318889028202c. * adding entry to changelog * Update CHANGELOG_PENDING.md Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * updating node.go * review fixes * fixes linter * fixing unit test * small fixes in comments * addressing review comments * addressing review comments 2 * reverting suggestion * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * do not expose brokenSignerDialerEndpoint * clean up logging * unifying methods shorten test time signer also drops * reenabling pings * improving testability + unit test * fixing go fmt + unit test * remove unused code * Addressing review comments * simplifying connection workflow * fix linter/go import issue * using base service quit * updating comment * Simplifying design + adjusting names * fixing linter issues * refactoring test harness + fixes * Addressing review comments * cleaning up * adding additional error check
5 years ago
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
5 years ago
privval: refactor Remote signers (#3370) This PR is related to #3107 and a continuation of #3351 It is important to emphasise that in the privval original design, client/server and listening/dialing roles are inverted and do not follow a conventional interaction. Given two hosts A and B: Host A is listener/client Host B is dialer/server (contains the secret key) When A requires a signature, it needs to wait for B to dial in before it can issue a request. A only accepts a single connection and any failure leads to dropping the connection and waiting for B to reconnect. The original rationale behind this design was based on security. Host B only allows outbound connections to a list of whitelisted hosts. It is not possible to reach B unless B dials in. There are no listening/open ports in B. This PR results in the following changes: Refactors ping/heartbeat to avoid previously existing race conditions. Separates transport (dialer/listener) from signing (client/server) concerns to simplify workflow. Unifies and abstracts away the differences between unix and tcp sockets. A single signer endpoint implementation unifies connection handling code (read/write/close/connection obj) The signer request handler (server side) is customizable to increase testability. Updates and extends unit tests A high level overview of the classes is as follows: Transport (endpoints): The following classes take care of establishing a connection SignerDialerEndpoint SignerListeningEndpoint SignerEndpoint groups common functionality (read/write/timeouts/etc.) Signing (client/server): The following classes take care of exchanging request/responses SignerClient SignerServer This PR also closes #3601 Commits: * refactoring - work in progress * reworking unit tests * Encapsulating and fixing unit tests * Improve tests * Clean up * Fix/improve unit tests * clean up tests * Improving service endpoint * fixing unit test * fix linter issues * avoid invalid cache values (improve later?) * complete implementation * wip * improved connection loop * Improve reconnections + fixing unit tests * addressing comments * small formatting changes * clean up * Update node/node.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * check during initialization * dropping connecting when writing fails * removing break * use t.log instead * unifying and using cmn.GetFreePort() * review fixes * reordering and unifying drop connection * closing instead of signalling * refactored service loop * removed superfluous brackets * GetPubKey can return errors * Revert "GetPubKey can return errors" This reverts commit 68c06f19b4650389d7e5ab1659b318889028202c. * adding entry to changelog * Update CHANGELOG_PENDING.md Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * updating node.go * review fixes * fixes linter * fixing unit test * small fixes in comments * addressing review comments * addressing review comments 2 * reverting suggestion * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * do not expose brokenSignerDialerEndpoint * clean up logging * unifying methods shorten test time signer also drops * reenabling pings * improving testability + unit test * fixing go fmt + unit test * remove unused code * Addressing review comments * simplifying connection workflow * fix linter/go import issue * using base service quit * updating comment * Simplifying design + adjusting names * fixing linter issues * refactoring test harness + fixes * Addressing review comments * cleaning up * adding additional error check
5 years ago
Close and retry a RemoteSigner on err (#2923) * Close and recreate a RemoteSigner on err * Update changelog * Address Anton's comments / suggestions: - update changelog - restart TCPVal - shut down on `ErrUnexpectedResponse` * re-init remote signer client with fresh connection if Ping fails - add/update TODOs in secret connection - rename tcp.go -> tcp_client.go, same with ipc to clarify their purpose * account for `conn returned by waitConnection can be `nil` - also add TODO about RemoteSigner conn field * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn * Tests for retrying: IPC / TCP - shorter info log on success - set conn and use it in tests to close conn - add rwmutex for conn field in IPC * comments and doc.go * fix ipc tests. fixes #2677 * use constants for tests * cleanup some error statements * fixes #2784, race in tests * remove print statement * minor fixes from review * update comment on sts spec * cosmetics * p2p/conn: add failing tests * p2p/conn: make SecretConnection thread safe * changelog * IPCVal signer refactor - use a .reset() method - don't use embedded RemoteSignerClient - guard RemoteSignerClient with mutex - drop the .conn - expose Close() on RemoteSignerClient * apply IPCVal refactor to TCPVal * remove mtx from RemoteSignerClient * consolidate IPCVal and TCPVal, fixes #3104 - done in tcp_client.go - now called SocketVal - takes a listener in the constructor - make tcpListener and unixListener contain all the differences * delete ipc files * introduce unix and tcp dialer for RemoteSigner * rename files - drop tcp_ prefix - rename priv_validator.go to file.go * bring back listener options * fix node * fix priv_val_server * fix node test * minor cleanup and comments
5 years ago
privval: refactor Remote signers (#3370) This PR is related to #3107 and a continuation of #3351 It is important to emphasise that in the privval original design, client/server and listening/dialing roles are inverted and do not follow a conventional interaction. Given two hosts A and B: Host A is listener/client Host B is dialer/server (contains the secret key) When A requires a signature, it needs to wait for B to dial in before it can issue a request. A only accepts a single connection and any failure leads to dropping the connection and waiting for B to reconnect. The original rationale behind this design was based on security. Host B only allows outbound connections to a list of whitelisted hosts. It is not possible to reach B unless B dials in. There are no listening/open ports in B. This PR results in the following changes: Refactors ping/heartbeat to avoid previously existing race conditions. Separates transport (dialer/listener) from signing (client/server) concerns to simplify workflow. Unifies and abstracts away the differences between unix and tcp sockets. A single signer endpoint implementation unifies connection handling code (read/write/close/connection obj) The signer request handler (server side) is customizable to increase testability. Updates and extends unit tests A high level overview of the classes is as follows: Transport (endpoints): The following classes take care of establishing a connection SignerDialerEndpoint SignerListeningEndpoint SignerEndpoint groups common functionality (read/write/timeouts/etc.) Signing (client/server): The following classes take care of exchanging request/responses SignerClient SignerServer This PR also closes #3601 Commits: * refactoring - work in progress * reworking unit tests * Encapsulating and fixing unit tests * Improve tests * Clean up * Fix/improve unit tests * clean up tests * Improving service endpoint * fixing unit test * fix linter issues * avoid invalid cache values (improve later?) * complete implementation * wip * improved connection loop * Improve reconnections + fixing unit tests * addressing comments * small formatting changes * clean up * Update node/node.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * check during initialization * dropping connecting when writing fails * removing break * use t.log instead * unifying and using cmn.GetFreePort() * review fixes * reordering and unifying drop connection * closing instead of signalling * refactored service loop * removed superfluous brackets * GetPubKey can return errors * Revert "GetPubKey can return errors" This reverts commit 68c06f19b4650389d7e5ab1659b318889028202c. * adding entry to changelog * Update CHANGELOG_PENDING.md Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_client.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_dialer_endpoint.go Co-Authored-By: jleni <juan.leni@zondax.ch> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: jleni <juan.leni@zondax.ch> * updating node.go * review fixes * fixes linter * fixing unit test * small fixes in comments * addressing review comments * addressing review comments 2 * reverting suggestion * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_client_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * Update privval/signer_listener_endpoint_test.go Co-Authored-By: Anton Kaliaev <anton.kalyaev@gmail.com> * do not expose brokenSignerDialerEndpoint * clean up logging * unifying methods shorten test time signer also drops * reenabling pings * improving testability + unit test * fixing go fmt + unit test * remove unused code * Addressing review comments * simplifying connection workflow * fix linter/go import issue * using base service quit * updating comment * Simplifying design + adjusting names * fixing linter issues * refactoring test harness + fixes * Addressing review comments * cleaning up * adding additional error check
5 years ago
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
fix non deterministic test failures and race in privval socket (#3258) * node: decrease retry conn timeout in test Should fix #3256 The retry timeout was set to the default, which is the same as the accept timeout, so it's no wonder this would fail. Here we decrease the retry timeout so we can try many times before the accept timeout. * p2p: increase handshake timeout in test This fails sometimes, presumably because the handshake timeout is so low (only 50ms). So increase it to 1s. Should fix #3187 * privval: fix race with ping. closes #3237 Pings happen in a go-routine and can happen concurrently with other messages. Since we use a request/response protocol, we expect to send a request and get back the corresponding response. But with pings happening concurrently, this assumption could be violated. We were using a mutex, but only a RWMutex, where the RLock was being held for sending messages - this was to allow the underlying connection to be replaced if it fails. Turns out we actually need to use a full lock (not just a read lock) to prevent multiple requests from happening concurrently. * node: fix test name. DelayedStop -> DelayedStart * autofile: Wait() method In the TestWALTruncate in consensus/wal_test.go we remove the WAL directory at the end of the test. However the wal.Stop() does not properly wait for the autofile group to finish shutting down. Hence it was possible that the group's go-routine is still running when the cleanup happens, which causes a panic since the directory disappeared. Here we add a Wait() method to properly wait until the go-routine exits so we can safely clean up. This fixes #2852.
5 years ago
fix non deterministic test failures and race in privval socket (#3258) * node: decrease retry conn timeout in test Should fix #3256 The retry timeout was set to the default, which is the same as the accept timeout, so it's no wonder this would fail. Here we decrease the retry timeout so we can try many times before the accept timeout. * p2p: increase handshake timeout in test This fails sometimes, presumably because the handshake timeout is so low (only 50ms). So increase it to 1s. Should fix #3187 * privval: fix race with ping. closes #3237 Pings happen in a go-routine and can happen concurrently with other messages. Since we use a request/response protocol, we expect to send a request and get back the corresponding response. But with pings happening concurrently, this assumption could be violated. We were using a mutex, but only a RWMutex, where the RLock was being held for sending messages - this was to allow the underlying connection to be replaced if it fails. Turns out we actually need to use a full lock (not just a read lock) to prevent multiple requests from happening concurrently. * node: fix test name. DelayedStop -> DelayedStart * autofile: Wait() method In the TestWALTruncate in consensus/wal_test.go we remove the WAL directory at the end of the test. However the wal.Stop() does not properly wait for the autofile group to finish shutting down. Hence it was possible that the group's go-routine is still running when the cleanup happens, which causes a panic since the directory disappeared. Here we add a Wait() method to properly wait until the go-routine exits so we can safely clean up. This fixes #2852.
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
  1. package node
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "net"
  8. "os"
  9. "syscall"
  10. "testing"
  11. "time"
  12. "github.com/stretchr/testify/assert"
  13. "github.com/stretchr/testify/require"
  14. dbm "github.com/tendermint/tm-db"
  15. "github.com/tendermint/tendermint/abci/example/kvstore"
  16. cfg "github.com/tendermint/tendermint/config"
  17. "github.com/tendermint/tendermint/crypto"
  18. "github.com/tendermint/tendermint/crypto/ed25519"
  19. "github.com/tendermint/tendermint/crypto/tmhash"
  20. "github.com/tendermint/tendermint/evidence"
  21. "github.com/tendermint/tendermint/libs/log"
  22. tmrand "github.com/tendermint/tendermint/libs/rand"
  23. "github.com/tendermint/tendermint/mempool"
  24. mempoolv0 "github.com/tendermint/tendermint/mempool/v0"
  25. "github.com/tendermint/tendermint/p2p"
  26. p2pmock "github.com/tendermint/tendermint/p2p/mock"
  27. "github.com/tendermint/tendermint/privval"
  28. "github.com/tendermint/tendermint/proxy"
  29. sm "github.com/tendermint/tendermint/state"
  30. "github.com/tendermint/tendermint/state/indexer"
  31. "github.com/tendermint/tendermint/store"
  32. "github.com/tendermint/tendermint/types"
  33. tmtime "github.com/tendermint/tendermint/types/time"
  34. )
  35. func TestNodeStartStop(t *testing.T) {
  36. config := cfg.ResetTestRoot("node_node_test")
  37. defer os.RemoveAll(config.RootDir)
  38. // create & start node
  39. n, err := DefaultNewNode(config, log.TestingLogger())
  40. require.NoError(t, err)
  41. err = n.Start()
  42. require.NoError(t, err)
  43. t.Logf("Started node %v", n.sw.NodeInfo())
  44. // wait for the node to produce a block
  45. blocksSub, err := n.EventBus().Subscribe(context.Background(), "node_test", types.EventQueryNewBlock)
  46. require.NoError(t, err)
  47. select {
  48. case <-blocksSub.Out():
  49. case <-blocksSub.Canceled():
  50. t.Fatal("blocksSub was canceled")
  51. case <-time.After(10 * time.Second):
  52. t.Fatal("timed out waiting for the node to produce a block")
  53. }
  54. // stop the node
  55. go func() {
  56. err = n.Stop()
  57. require.NoError(t, err)
  58. }()
  59. select {
  60. case <-n.Quit():
  61. case <-time.After(5 * time.Second):
  62. pid := os.Getpid()
  63. p, err := os.FindProcess(pid)
  64. if err != nil {
  65. panic(err)
  66. }
  67. err = p.Signal(syscall.SIGABRT)
  68. fmt.Println(err)
  69. t.Fatal("timed out waiting for shutdown")
  70. }
  71. }
  72. func TestNodeDelayedStart(t *testing.T) {
  73. config := cfg.ResetTestRoot("node_delayed_start_test")
  74. defer os.RemoveAll(config.RootDir)
  75. now := tmtime.Now()
  76. // create & start node
  77. n, err := DefaultNewNode(config, log.TestingLogger())
  78. n.GenesisDoc().GenesisTime = now.Add(2 * time.Second)
  79. require.NoError(t, err)
  80. err = n.Start()
  81. require.NoError(t, err)
  82. defer n.Stop() //nolint:errcheck // ignore for tests
  83. startTime := tmtime.Now()
  84. assert.Equal(t, true, startTime.After(n.GenesisDoc().GenesisTime))
  85. }
  86. func TestNodeSetAppVersion(t *testing.T) {
  87. config := cfg.ResetTestRoot("node_app_version_test")
  88. defer os.RemoveAll(config.RootDir)
  89. // create & start node
  90. n, err := DefaultNewNode(config, log.TestingLogger())
  91. require.NoError(t, err)
  92. // default config uses the kvstore app
  93. var appVersion uint64 = kvstore.ProtocolVersion
  94. // check version is set in state
  95. state, err := n.stateStore.Load()
  96. require.NoError(t, err)
  97. assert.Equal(t, state.Version.Consensus.App, appVersion)
  98. // check version is set in node info
  99. assert.Equal(t, n.nodeInfo.ProtocolVersion.App, appVersion)
  100. }
  101. func TestNodeSetPrivValTCP(t *testing.T) {
  102. addr := "tcp://" + testFreeAddr(t)
  103. config := cfg.ResetTestRoot("node_priv_val_tcp_test")
  104. defer os.RemoveAll(config.RootDir)
  105. config.PrivValidator.ListenAddr = addr
  106. dialer := privval.DialTCPFn(addr, 100*time.Millisecond, ed25519.GenPrivKey())
  107. dialerEndpoint := privval.NewSignerDialerEndpoint(
  108. log.TestingLogger(),
  109. dialer,
  110. )
  111. privval.SignerDialerEndpointTimeoutReadWrite(100 * time.Millisecond)(dialerEndpoint)
  112. signerServer := privval.NewSignerServer(
  113. dialerEndpoint,
  114. config.ChainID(),
  115. types.NewMockPV(),
  116. )
  117. go func() {
  118. err := signerServer.Start()
  119. if err != nil {
  120. panic(err)
  121. }
  122. }()
  123. defer signerServer.Stop() //nolint:errcheck // ignore for tests
  124. n, err := DefaultNewNode(config, log.TestingLogger())
  125. require.NoError(t, err)
  126. assert.IsType(t, &privval.RetrySignerClient{}, n.PrivValidator())
  127. }
  128. // address without a protocol must result in error
  129. func TestPrivValidatorListenAddrNoProtocol(t *testing.T) {
  130. addrNoPrefix := testFreeAddr(t)
  131. config := cfg.ResetTestRoot("node_priv_val_tcp_test")
  132. defer os.RemoveAll(config.RootDir)
  133. config.PrivValidator.ListenAddr = addrNoPrefix
  134. _, err := DefaultNewNode(config, log.TestingLogger())
  135. assert.Error(t, err)
  136. }
  137. func TestNodeSetPrivValIPC(t *testing.T) {
  138. tmpfile := "/tmp/kms." + tmrand.Str(6) + ".sock"
  139. defer os.Remove(tmpfile) // clean up
  140. config := cfg.ResetTestRoot("node_priv_val_tcp_test")
  141. defer os.RemoveAll(config.RootDir)
  142. config.PrivValidator.ListenAddr = "unix://" + tmpfile
  143. dialer := privval.DialUnixFn(tmpfile)
  144. dialerEndpoint := privval.NewSignerDialerEndpoint(
  145. log.TestingLogger(),
  146. dialer,
  147. )
  148. privval.SignerDialerEndpointTimeoutReadWrite(100 * time.Millisecond)(dialerEndpoint)
  149. pvsc := privval.NewSignerServer(
  150. dialerEndpoint,
  151. config.ChainID(),
  152. types.NewMockPV(),
  153. )
  154. go func() {
  155. err := pvsc.Start()
  156. require.NoError(t, err)
  157. }()
  158. defer pvsc.Stop() //nolint:errcheck // ignore for tests
  159. n, err := DefaultNewNode(config, log.TestingLogger())
  160. require.NoError(t, err)
  161. assert.IsType(t, &privval.RetrySignerClient{}, n.PrivValidator())
  162. }
  163. // testFreeAddr claims a free port so we don't block on listener being ready.
  164. func testFreeAddr(t *testing.T) string {
  165. ln, err := net.Listen("tcp", "127.0.0.1:0")
  166. require.NoError(t, err)
  167. defer ln.Close()
  168. return fmt.Sprintf("127.0.0.1:%d", ln.Addr().(*net.TCPAddr).Port)
  169. }
  170. // create a proposal block using real and full
  171. // mempool and evidence pool and validate it.
  172. func TestCreateProposalBlock(t *testing.T) {
  173. config := cfg.ResetTestRoot("node_create_proposal")
  174. defer os.RemoveAll(config.RootDir)
  175. cc := proxy.NewLocalClientCreator(kvstore.NewApplication())
  176. proxyApp := proxy.NewAppConns(cc)
  177. err := proxyApp.Start()
  178. require.Nil(t, err)
  179. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  180. logger := log.TestingLogger()
  181. const height int64 = 1
  182. state, stateDB, privVals := state(1, height)
  183. stateStore := sm.NewStore(stateDB)
  184. maxBytes := 16384
  185. const partSize uint32 = 256
  186. maxEvidenceBytes := int64(maxBytes / 2)
  187. state.ConsensusParams.Block.MaxBytes = int64(maxBytes)
  188. state.ConsensusParams.Evidence.MaxBytes = maxEvidenceBytes
  189. proposerAddr, _ := state.Validators.GetByIndex(0)
  190. mp := mempoolv0.NewCListMempool(
  191. config.Mempool,
  192. proxyApp.Mempool(),
  193. state.LastBlockHeight,
  194. mempoolv0.WithMetrics(mempool.NopMetrics()),
  195. mempoolv0.WithPreCheck(sm.TxPreCheck(state)),
  196. mempoolv0.WithPostCheck(sm.TxPostCheck(state)),
  197. )
  198. mp.SetLogger(logger)
  199. // Make EvidencePool
  200. evidenceDB := dbm.NewMemDB()
  201. blockStore := store.NewBlockStore(dbm.NewMemDB())
  202. evidencePool, err := evidence.NewPool(logger, evidenceDB, stateStore, blockStore)
  203. require.NoError(t, err)
  204. // fill the evidence pool with more evidence
  205. // than can fit in a block
  206. var currentBytes int64 = 0
  207. for currentBytes <= maxEvidenceBytes {
  208. ev := types.NewMockDuplicateVoteEvidenceWithValidator(height, time.Now(), privVals[0], "test-chain")
  209. currentBytes += int64(len(ev.Bytes()))
  210. evidencePool.ReportConflictingVotes(ev.VoteA, ev.VoteB)
  211. }
  212. evList, size := evidencePool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  213. require.Less(t, size, state.ConsensusParams.Evidence.MaxBytes+1)
  214. evData := &types.EvidenceData{Evidence: evList}
  215. require.EqualValues(t, size, evData.ByteSize())
  216. // fill the mempool with more txs
  217. // than can fit in a block
  218. txLength := 100
  219. for i := 0; i <= maxBytes/txLength; i++ {
  220. tx := tmrand.Bytes(txLength)
  221. err := mp.CheckTx(tx, nil, mempool.TxInfo{})
  222. assert.NoError(t, err)
  223. }
  224. blockExec := sm.NewBlockExecutor(
  225. stateStore,
  226. logger,
  227. proxyApp.Consensus(),
  228. mp,
  229. evidencePool,
  230. )
  231. commit := types.NewCommit(height-1, 0, types.BlockID{}, nil)
  232. block, _ := blockExec.CreateProposalBlock(
  233. height,
  234. state, commit,
  235. proposerAddr,
  236. )
  237. // check that the part set does not exceed the maximum block size
  238. partSet := block.MakePartSet(partSize)
  239. assert.Less(t, partSet.ByteSize(), int64(maxBytes))
  240. partSetFromHeader := types.NewPartSetFromHeader(partSet.Header())
  241. for partSetFromHeader.Count() < partSetFromHeader.Total() {
  242. added, err := partSetFromHeader.AddPart(partSet.GetPart(int(partSetFromHeader.Count())))
  243. require.NoError(t, err)
  244. require.True(t, added)
  245. }
  246. assert.EqualValues(t, partSetFromHeader.ByteSize(), partSet.ByteSize())
  247. err = blockExec.ValidateBlock(state, block)
  248. assert.NoError(t, err)
  249. }
  250. func TestMaxTxsProposalBlockSize(t *testing.T) {
  251. config := cfg.ResetTestRoot("node_create_proposal")
  252. defer os.RemoveAll(config.RootDir)
  253. cc := proxy.NewLocalClientCreator(kvstore.NewApplication())
  254. proxyApp := proxy.NewAppConns(cc)
  255. err := proxyApp.Start()
  256. require.Nil(t, err)
  257. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  258. logger := log.TestingLogger()
  259. const height int64 = 1
  260. state, stateDB, _ := state(1, height)
  261. stateStore := sm.NewStore(stateDB)
  262. const maxBytes int64 = 16384
  263. const partSize uint32 = 256
  264. state.ConsensusParams.Block.MaxBytes = maxBytes
  265. proposerAddr, _ := state.Validators.GetByIndex(0)
  266. // Make Mempool
  267. mp := mempoolv0.NewCListMempool(
  268. config.Mempool,
  269. proxyApp.Mempool(),
  270. state.LastBlockHeight,
  271. mempoolv0.WithMetrics(mempool.NopMetrics()),
  272. mempoolv0.WithPreCheck(sm.TxPreCheck(state)),
  273. mempoolv0.WithPostCheck(sm.TxPostCheck(state)),
  274. )
  275. mp.SetLogger(logger)
  276. // fill the mempool with one txs just below the maximum size
  277. txLength := int(types.MaxDataBytesNoEvidence(maxBytes, 1))
  278. tx := tmrand.Bytes(txLength - 4) // to account for the varint
  279. err = mp.CheckTx(tx, nil, mempool.TxInfo{})
  280. assert.NoError(t, err)
  281. blockExec := sm.NewBlockExecutor(
  282. stateStore,
  283. logger,
  284. proxyApp.Consensus(),
  285. mp,
  286. sm.EmptyEvidencePool{},
  287. )
  288. commit := types.NewCommit(height-1, 0, types.BlockID{}, nil)
  289. block, _ := blockExec.CreateProposalBlock(
  290. height,
  291. state, commit,
  292. proposerAddr,
  293. )
  294. pb, err := block.ToProto()
  295. require.NoError(t, err)
  296. assert.Less(t, int64(pb.Size()), maxBytes)
  297. // check that the part set does not exceed the maximum block size
  298. partSet := block.MakePartSet(partSize)
  299. assert.EqualValues(t, partSet.ByteSize(), int64(pb.Size()))
  300. }
  301. func TestMaxProposalBlockSize(t *testing.T) {
  302. config := cfg.ResetTestRoot("node_create_proposal")
  303. defer os.RemoveAll(config.RootDir)
  304. cc := proxy.NewLocalClientCreator(kvstore.NewApplication())
  305. proxyApp := proxy.NewAppConns(cc)
  306. err := proxyApp.Start()
  307. require.Nil(t, err)
  308. defer proxyApp.Stop() //nolint:errcheck // ignore for tests
  309. logger := log.TestingLogger()
  310. state, stateDB, _ := state(types.MaxVotesCount, int64(1))
  311. stateStore := sm.NewStore(stateDB)
  312. const maxBytes int64 = 1024 * 1024 * 2
  313. state.ConsensusParams.Block.MaxBytes = maxBytes
  314. proposerAddr, _ := state.Validators.GetByIndex(0)
  315. // Make Mempool
  316. mp := mempoolv0.NewCListMempool(
  317. config.Mempool,
  318. proxyApp.Mempool(),
  319. state.LastBlockHeight,
  320. mempoolv0.WithMetrics(mempool.NopMetrics()),
  321. mempoolv0.WithPreCheck(sm.TxPreCheck(state)),
  322. mempoolv0.WithPostCheck(sm.TxPostCheck(state)),
  323. )
  324. mp.SetLogger(logger)
  325. // fill the mempool with one txs just below the maximum size
  326. txLength := int(types.MaxDataBytesNoEvidence(maxBytes, types.MaxVotesCount))
  327. tx := tmrand.Bytes(txLength - 6) // to account for the varint
  328. err = mp.CheckTx(tx, nil, mempool.TxInfo{})
  329. assert.NoError(t, err)
  330. // now produce more txs than what a normal block can hold with 10 smaller txs
  331. // At the end of the test, only the single big tx should be added
  332. for i := 0; i < 10; i++ {
  333. tx := tmrand.Bytes(10)
  334. err = mp.CheckTx(tx, nil, mempool.TxInfo{})
  335. assert.NoError(t, err)
  336. }
  337. blockExec := sm.NewBlockExecutor(
  338. stateStore,
  339. logger,
  340. proxyApp.Consensus(),
  341. mp,
  342. sm.EmptyEvidencePool{},
  343. )
  344. blockID := types.BlockID{
  345. Hash: tmhash.Sum([]byte("blockID_hash")),
  346. PartSetHeader: types.PartSetHeader{
  347. Total: math.MaxInt32,
  348. Hash: tmhash.Sum([]byte("blockID_part_set_header_hash")),
  349. },
  350. }
  351. timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
  352. // change state in order to produce the largest accepted header
  353. state.LastBlockID = blockID
  354. state.LastBlockHeight = math.MaxInt64 - 1
  355. state.LastBlockTime = timestamp
  356. state.LastResultsHash = tmhash.Sum([]byte("last_results_hash"))
  357. state.AppHash = tmhash.Sum([]byte("app_hash"))
  358. state.Version.Consensus.Block = math.MaxInt64
  359. state.Version.Consensus.App = math.MaxInt64
  360. maxChainID := ""
  361. for i := 0; i < types.MaxChainIDLen; i++ {
  362. maxChainID += "𠜎"
  363. }
  364. state.ChainID = maxChainID
  365. cs := types.CommitSig{
  366. BlockIDFlag: types.BlockIDFlagNil,
  367. ValidatorAddress: crypto.AddressHash([]byte("validator_address")),
  368. Timestamp: timestamp,
  369. Signature: crypto.CRandBytes(types.MaxSignatureSize),
  370. }
  371. commit := &types.Commit{
  372. Height: math.MaxInt64,
  373. Round: math.MaxInt32,
  374. BlockID: blockID,
  375. }
  376. // add maximum amount of signatures to a single commit
  377. for i := 0; i < types.MaxVotesCount; i++ {
  378. commit.Signatures = append(commit.Signatures, cs)
  379. }
  380. block, partSet := blockExec.CreateProposalBlock(
  381. math.MaxInt64,
  382. state, commit,
  383. proposerAddr,
  384. )
  385. // this ensures that the header is at max size
  386. block.Header.Time = timestamp
  387. pb, err := block.ToProto()
  388. require.NoError(t, err)
  389. // require that the header and commit be the max possible size
  390. require.Equal(t, int64(pb.Header.Size()), types.MaxHeaderBytes)
  391. require.Equal(t, int64(pb.LastCommit.Size()), types.MaxCommitBytes(types.MaxVotesCount))
  392. // make sure that the block is less than the max possible size
  393. assert.Equal(t, int64(pb.Size()), maxBytes)
  394. // because of the proto overhead we expect the part set bytes to be equal or
  395. // less than the pb block size
  396. assert.LessOrEqual(t, partSet.ByteSize(), int64(pb.Size()))
  397. }
  398. func TestNodeNewNodeCustomReactors(t *testing.T) {
  399. config := cfg.ResetTestRoot("node_new_node_custom_reactors_test")
  400. defer os.RemoveAll(config.RootDir)
  401. cr := p2pmock.NewReactor()
  402. customBlockchainReactor := p2pmock.NewReactor()
  403. nodeKey, err := p2p.LoadOrGenNodeKey(config.NodeKeyFile())
  404. require.NoError(t, err)
  405. pval, err := privval.LoadOrGenFilePV(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile())
  406. require.NoError(t, err)
  407. appClient, closer := proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir())
  408. t.Cleanup(func() { closer.Close() })
  409. n, err := NewNode(config,
  410. pval,
  411. nodeKey,
  412. appClient,
  413. DefaultGenesisDocProviderFunc(config),
  414. DefaultDBProvider,
  415. DefaultMetricsProvider(config.Instrumentation),
  416. log.TestingLogger(),
  417. CustomReactors(map[string]p2p.Reactor{"FOO": cr, "BLOCKCHAIN": customBlockchainReactor}),
  418. )
  419. require.NoError(t, err)
  420. err = n.Start()
  421. require.NoError(t, err)
  422. defer n.Stop() //nolint:errcheck // ignore for tests
  423. assert.True(t, cr.IsRunning())
  424. assert.Equal(t, cr, n.Switch().Reactor("FOO"))
  425. assert.True(t, customBlockchainReactor.IsRunning())
  426. assert.Equal(t, customBlockchainReactor, n.Switch().Reactor("BLOCKCHAIN"))
  427. }
  428. func TestNodeNewSeedNode(t *testing.T) {
  429. config := cfg.ResetTestRoot("node_new_node_custom_reactors_test")
  430. config.Mode = cfg.ModeSeed
  431. defer os.RemoveAll(config.RootDir)
  432. nodeKey, err := p2p.LoadOrGenNodeKey(config.NodeKeyFile())
  433. require.NoError(t, err)
  434. n, err := NewSeedNode(config,
  435. DefaultDBProvider,
  436. nodeKey,
  437. DefaultGenesisDocProviderFunc(config),
  438. log.TestingLogger(),
  439. )
  440. require.NoError(t, err)
  441. err = n.Start()
  442. require.NoError(t, err)
  443. assert.True(t, n.pexReactor.IsRunning())
  444. }
  445. func TestNodeSetEventSink(t *testing.T) {
  446. config := cfg.ResetTestRoot("node_app_version_test")
  447. defer os.RemoveAll(config.RootDir)
  448. // create & start node
  449. n, err := DefaultNewNode(config, log.TestingLogger())
  450. require.NoError(t, err)
  451. assert.Equal(t, 1, len(n.eventSinks))
  452. assert.Equal(t, indexer.KV, n.eventSinks[0].Type())
  453. config.TxIndex.Indexer = []string{"null"}
  454. n, err = DefaultNewNode(config, log.TestingLogger())
  455. require.NoError(t, err)
  456. assert.Equal(t, 1, len(n.eventSinks))
  457. assert.Equal(t, indexer.NULL, n.eventSinks[0].Type())
  458. config.TxIndex.Indexer = []string{"null", "kv"}
  459. n, err = DefaultNewNode(config, log.TestingLogger())
  460. require.NoError(t, err)
  461. assert.Equal(t, 1, len(n.eventSinks))
  462. assert.Equal(t, indexer.NULL, n.eventSinks[0].Type())
  463. config.TxIndex.Indexer = []string{"kvv"}
  464. n, err = DefaultNewNode(config, log.TestingLogger())
  465. assert.Nil(t, n)
  466. assert.Equal(t, errors.New("unsupported event sink type"), err)
  467. config.TxIndex.Indexer = []string{}
  468. n, err = DefaultNewNode(config, log.TestingLogger())
  469. require.NoError(t, err)
  470. assert.Equal(t, 1, len(n.eventSinks))
  471. assert.Equal(t, indexer.NULL, n.eventSinks[0].Type())
  472. config.TxIndex.Indexer = []string{"psql"}
  473. n, err = DefaultNewNode(config, log.TestingLogger())
  474. assert.Nil(t, n)
  475. assert.Equal(t, errors.New("the psql connection settings cannot be empty"), err)
  476. var psqlConn = "test"
  477. config.TxIndex.Indexer = []string{"psql"}
  478. config.TxIndex.PsqlConn = psqlConn
  479. n, err = DefaultNewNode(config, log.TestingLogger())
  480. require.NoError(t, err)
  481. assert.Equal(t, 1, len(n.eventSinks))
  482. assert.Equal(t, indexer.PSQL, n.eventSinks[0].Type())
  483. n.OnStop()
  484. config.TxIndex.Indexer = []string{"psql", "kv"}
  485. config.TxIndex.PsqlConn = psqlConn
  486. n, err = DefaultNewNode(config, log.TestingLogger())
  487. require.NoError(t, err)
  488. assert.Equal(t, 2, len(n.eventSinks))
  489. // we use map to filter the duplicated sinks, so it's not guarantee the order when append sinks.
  490. if n.eventSinks[0].Type() == indexer.KV {
  491. assert.Equal(t, indexer.PSQL, n.eventSinks[1].Type())
  492. } else {
  493. assert.Equal(t, indexer.PSQL, n.eventSinks[0].Type())
  494. assert.Equal(t, indexer.KV, n.eventSinks[1].Type())
  495. }
  496. n.OnStop()
  497. config.TxIndex.Indexer = []string{"kv", "psql"}
  498. config.TxIndex.PsqlConn = psqlConn
  499. n, err = DefaultNewNode(config, log.TestingLogger())
  500. require.NoError(t, err)
  501. assert.Equal(t, 2, len(n.eventSinks))
  502. if n.eventSinks[0].Type() == indexer.KV {
  503. assert.Equal(t, indexer.PSQL, n.eventSinks[1].Type())
  504. } else {
  505. assert.Equal(t, indexer.PSQL, n.eventSinks[0].Type())
  506. assert.Equal(t, indexer.KV, n.eventSinks[1].Type())
  507. }
  508. n.OnStop()
  509. var e = errors.New("found duplicated sinks, please check the tx-index section in the config.toml")
  510. config.TxIndex.Indexer = []string{"psql", "kv", "Kv"}
  511. config.TxIndex.PsqlConn = psqlConn
  512. _, err = DefaultNewNode(config, log.TestingLogger())
  513. require.Error(t, err)
  514. assert.Equal(t, e, err)
  515. config.TxIndex.Indexer = []string{"Psql", "kV", "kv", "pSql"}
  516. config.TxIndex.PsqlConn = psqlConn
  517. _, err = DefaultNewNode(config, log.TestingLogger())
  518. require.Error(t, err)
  519. assert.Equal(t, e, err)
  520. }
  521. func state(nVals int, height int64) (sm.State, dbm.DB, []types.PrivValidator) {
  522. privVals := make([]types.PrivValidator, nVals)
  523. vals := make([]types.GenesisValidator, nVals)
  524. for i := 0; i < nVals; i++ {
  525. privVal := types.NewMockPV()
  526. privVals[i] = privVal
  527. vals[i] = types.GenesisValidator{
  528. Address: privVal.PrivKey.PubKey().Address(),
  529. PubKey: privVal.PrivKey.PubKey(),
  530. Power: 1000,
  531. Name: fmt.Sprintf("test%d", i),
  532. }
  533. }
  534. s, _ := sm.MakeGenesisState(&types.GenesisDoc{
  535. ChainID: "test-chain",
  536. Validators: vals,
  537. AppHash: nil,
  538. })
  539. // save validators to db for 2 heights
  540. stateDB := dbm.NewMemDB()
  541. stateStore := sm.NewStore(stateDB)
  542. if err := stateStore.Save(s); err != nil {
  543. panic(err)
  544. }
  545. for i := 1; i < int(height); i++ {
  546. s.LastBlockHeight++
  547. s.LastValidators = s.Validators.Copy()
  548. if err := stateStore.Save(s); err != nil {
  549. panic(err)
  550. }
  551. }
  552. return s, stateDB, privVals
  553. }