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.

740 lines
20 KiB

cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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.
6 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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.
6 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 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
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
  1. package node
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "math"
  7. "net"
  8. "os"
  9. "testing"
  10. "time"
  11. "github.com/fortytw2/leaktest"
  12. "github.com/stretchr/testify/assert"
  13. "github.com/stretchr/testify/require"
  14. dbm "github.com/tendermint/tm-db"
  15. abciclient "github.com/tendermint/tendermint/abci/client"
  16. "github.com/tendermint/tendermint/abci/example/kvstore"
  17. "github.com/tendermint/tendermint/config"
  18. "github.com/tendermint/tendermint/crypto"
  19. "github.com/tendermint/tendermint/crypto/ed25519"
  20. "github.com/tendermint/tendermint/crypto/tmhash"
  21. "github.com/tendermint/tendermint/internal/eventbus"
  22. "github.com/tendermint/tendermint/internal/evidence"
  23. "github.com/tendermint/tendermint/internal/mempool"
  24. "github.com/tendermint/tendermint/internal/proxy"
  25. "github.com/tendermint/tendermint/internal/pubsub"
  26. sm "github.com/tendermint/tendermint/internal/state"
  27. "github.com/tendermint/tendermint/internal/state/indexer"
  28. "github.com/tendermint/tendermint/internal/store"
  29. "github.com/tendermint/tendermint/internal/test/factory"
  30. "github.com/tendermint/tendermint/libs/log"
  31. tmrand "github.com/tendermint/tendermint/libs/rand"
  32. "github.com/tendermint/tendermint/libs/service"
  33. tmtime "github.com/tendermint/tendermint/libs/time"
  34. "github.com/tendermint/tendermint/privval"
  35. "github.com/tendermint/tendermint/types"
  36. )
  37. func TestNodeStartStop(t *testing.T) {
  38. cfg, err := config.ResetTestRoot("node_node_test")
  39. require.NoError(t, err)
  40. defer os.RemoveAll(cfg.RootDir)
  41. ctx, bcancel := context.WithCancel(context.Background())
  42. defer bcancel()
  43. logger := log.NewTestingLogger(t)
  44. // create & start node
  45. ns, err := newDefaultNode(ctx, cfg, logger)
  46. require.NoError(t, err)
  47. n, ok := ns.(*nodeImpl)
  48. require.True(t, ok)
  49. t.Cleanup(func() {
  50. if n.IsRunning() {
  51. bcancel()
  52. n.Wait()
  53. }
  54. })
  55. require.NoError(t, n.Start(ctx))
  56. // wait for the node to produce a block
  57. tctx, cancel := context.WithTimeout(ctx, time.Second)
  58. defer cancel()
  59. blocksSub, err := n.EventBus().SubscribeWithArgs(tctx, pubsub.SubscribeArgs{
  60. ClientID: "node_test",
  61. Query: types.EventQueryNewBlock,
  62. })
  63. require.NoError(t, err)
  64. _, err = blocksSub.Next(tctx)
  65. require.NoError(t, err, "waiting for event")
  66. cancel() // stop the subscription context
  67. bcancel() // stop the base context
  68. n.Wait()
  69. require.False(t, n.IsRunning(), "node must shut down")
  70. }
  71. func getTestNode(ctx context.Context, t *testing.T, conf *config.Config, logger log.Logger) *nodeImpl {
  72. t.Helper()
  73. ctx, cancel := context.WithCancel(ctx)
  74. defer cancel()
  75. ns, err := newDefaultNode(ctx, conf, logger)
  76. require.NoError(t, err)
  77. n, ok := ns.(*nodeImpl)
  78. require.True(t, ok)
  79. t.Cleanup(func() {
  80. cancel()
  81. if n.IsRunning() {
  82. ns.Wait()
  83. }
  84. })
  85. return n
  86. }
  87. func TestNodeDelayedStart(t *testing.T) {
  88. cfg, err := config.ResetTestRoot("node_delayed_start_test")
  89. require.NoError(t, err)
  90. defer os.RemoveAll(cfg.RootDir)
  91. now := tmtime.Now()
  92. ctx, cancel := context.WithCancel(context.Background())
  93. defer cancel()
  94. logger := log.NewTestingLogger(t)
  95. // create & start node
  96. n := getTestNode(ctx, t, cfg, logger)
  97. n.GenesisDoc().GenesisTime = now.Add(2 * time.Second)
  98. require.NoError(t, n.Start(ctx))
  99. startTime := tmtime.Now()
  100. assert.Equal(t, true, startTime.After(n.GenesisDoc().GenesisTime))
  101. }
  102. func TestNodeSetAppVersion(t *testing.T) {
  103. cfg, err := config.ResetTestRoot("node_app_version_test")
  104. require.NoError(t, err)
  105. defer os.RemoveAll(cfg.RootDir)
  106. ctx, cancel := context.WithCancel(context.Background())
  107. defer cancel()
  108. logger := log.NewTestingLogger(t)
  109. // create node
  110. n := getTestNode(ctx, t, cfg, logger)
  111. // default config uses the kvstore app
  112. appVersion := kvstore.ProtocolVersion
  113. // check version is set in state
  114. state, err := n.stateStore.Load()
  115. require.NoError(t, err)
  116. assert.Equal(t, state.Version.Consensus.App, appVersion)
  117. // check version is set in node info
  118. assert.Equal(t, n.nodeInfo.ProtocolVersion.App, appVersion)
  119. }
  120. func TestNodeSetPrivValTCP(t *testing.T) {
  121. addr := "tcp://" + testFreeAddr(t)
  122. t.Cleanup(leaktest.Check(t))
  123. ctx, cancel := context.WithCancel(context.Background())
  124. defer cancel()
  125. logger := log.NewTestingLogger(t)
  126. cfg, err := config.ResetTestRoot("node_priv_val_tcp_test")
  127. require.NoError(t, err)
  128. defer os.RemoveAll(cfg.RootDir)
  129. cfg.PrivValidator.ListenAddr = addr
  130. dialer := privval.DialTCPFn(addr, 100*time.Millisecond, ed25519.GenPrivKey())
  131. dialerEndpoint := privval.NewSignerDialerEndpoint(logger, dialer)
  132. privval.SignerDialerEndpointTimeoutReadWrite(100 * time.Millisecond)(dialerEndpoint)
  133. signerServer := privval.NewSignerServer(
  134. dialerEndpoint,
  135. cfg.ChainID(),
  136. types.NewMockPV(),
  137. )
  138. go func() {
  139. err := signerServer.Start(ctx)
  140. require.NoError(t, err)
  141. }()
  142. defer signerServer.Stop() //nolint:errcheck // ignore for tests
  143. genDoc, err := defaultGenesisDocProviderFunc(cfg)()
  144. require.NoError(t, err)
  145. pval, err := createPrivval(ctx, logger, cfg, genDoc, nil)
  146. require.NoError(t, err)
  147. assert.IsType(t, &privval.RetrySignerClient{}, pval)
  148. }
  149. // address without a protocol must result in error
  150. func TestPrivValidatorListenAddrNoProtocol(t *testing.T) {
  151. ctx, cancel := context.WithCancel(context.Background())
  152. defer cancel()
  153. addrNoPrefix := testFreeAddr(t)
  154. cfg, err := config.ResetTestRoot("node_priv_val_tcp_test")
  155. require.NoError(t, err)
  156. defer os.RemoveAll(cfg.RootDir)
  157. cfg.PrivValidator.ListenAddr = addrNoPrefix
  158. logger := log.NewTestingLogger(t)
  159. n, err := newDefaultNode(ctx, cfg, logger)
  160. assert.Error(t, err)
  161. if n != nil && n.IsRunning() {
  162. cancel()
  163. n.Wait()
  164. }
  165. }
  166. func TestNodeSetPrivValIPC(t *testing.T) {
  167. tmpfile := "/tmp/kms." + tmrand.Str(6) + ".sock"
  168. defer os.Remove(tmpfile) // clean up
  169. ctx, cancel := context.WithCancel(context.Background())
  170. defer cancel()
  171. cfg, err := config.ResetTestRoot("node_priv_val_tcp_test")
  172. require.NoError(t, err)
  173. defer os.RemoveAll(cfg.RootDir)
  174. cfg.PrivValidator.ListenAddr = "unix://" + tmpfile
  175. logger := log.NewTestingLogger(t)
  176. dialer := privval.DialUnixFn(tmpfile)
  177. dialerEndpoint := privval.NewSignerDialerEndpoint(logger, dialer)
  178. privval.SignerDialerEndpointTimeoutReadWrite(100 * time.Millisecond)(dialerEndpoint)
  179. pvsc := privval.NewSignerServer(
  180. dialerEndpoint,
  181. cfg.ChainID(),
  182. types.NewMockPV(),
  183. )
  184. go func() {
  185. err := pvsc.Start(ctx)
  186. require.NoError(t, err)
  187. }()
  188. defer pvsc.Stop() //nolint:errcheck // ignore for tests
  189. genDoc, err := defaultGenesisDocProviderFunc(cfg)()
  190. require.NoError(t, err)
  191. pval, err := createPrivval(ctx, logger, cfg, genDoc, nil)
  192. require.NoError(t, err)
  193. assert.IsType(t, &privval.RetrySignerClient{}, pval)
  194. }
  195. // testFreeAddr claims a free port so we don't block on listener being ready.
  196. func testFreeAddr(t *testing.T) string {
  197. ln, err := net.Listen("tcp", "127.0.0.1:0")
  198. require.NoError(t, err)
  199. defer ln.Close()
  200. return fmt.Sprintf("127.0.0.1:%d", ln.Addr().(*net.TCPAddr).Port)
  201. }
  202. // create a proposal block using real and full
  203. // mempool and evidence pool and validate it.
  204. func TestCreateProposalBlock(t *testing.T) {
  205. ctx, cancel := context.WithCancel(context.Background())
  206. defer cancel()
  207. cfg, err := config.ResetTestRoot("node_create_proposal")
  208. require.NoError(t, err)
  209. defer os.RemoveAll(cfg.RootDir)
  210. logger := log.NewTestingLogger(t)
  211. cc := abciclient.NewLocalCreator(kvstore.NewApplication())
  212. proxyApp := proxy.NewAppConns(cc, logger, proxy.NopMetrics())
  213. err = proxyApp.Start(ctx)
  214. require.NoError(t, err)
  215. const height int64 = 1
  216. state, stateDB, privVals := state(t, 1, height)
  217. stateStore := sm.NewStore(stateDB)
  218. maxBytes := 16384
  219. const partSize uint32 = 256
  220. maxEvidenceBytes := int64(maxBytes / 2)
  221. state.ConsensusParams.Block.MaxBytes = int64(maxBytes)
  222. state.ConsensusParams.Evidence.MaxBytes = maxEvidenceBytes
  223. proposerAddr, _ := state.Validators.GetByIndex(0)
  224. mp := mempool.NewTxMempool(
  225. logger.With("module", "mempool"),
  226. cfg.Mempool,
  227. proxyApp.Mempool(),
  228. state.LastBlockHeight,
  229. )
  230. // Make EvidencePool
  231. evidenceDB := dbm.NewMemDB()
  232. blockStore := store.NewBlockStore(dbm.NewMemDB())
  233. evidencePool, err := evidence.NewPool(logger, evidenceDB, stateStore, blockStore)
  234. require.NoError(t, err)
  235. // fill the evidence pool with more evidence
  236. // than can fit in a block
  237. var currentBytes int64
  238. for currentBytes <= maxEvidenceBytes {
  239. ev, err := types.NewMockDuplicateVoteEvidenceWithValidator(ctx, height, time.Now(), privVals[0], "test-chain")
  240. require.NoError(t, err)
  241. currentBytes += int64(len(ev.Bytes()))
  242. evidencePool.ReportConflictingVotes(ev.VoteA, ev.VoteB)
  243. }
  244. evList, size := evidencePool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  245. require.Less(t, size, state.ConsensusParams.Evidence.MaxBytes+1)
  246. evData := &types.EvidenceData{Evidence: evList}
  247. require.EqualValues(t, size, evData.ByteSize())
  248. // fill the mempool with more txs
  249. // than can fit in a block
  250. txLength := 100
  251. for i := 0; i <= maxBytes/txLength; i++ {
  252. tx := tmrand.Bytes(txLength)
  253. err := mp.CheckTx(ctx, tx, nil, mempool.TxInfo{})
  254. assert.NoError(t, err)
  255. }
  256. blockExec := sm.NewBlockExecutor(
  257. stateStore,
  258. logger,
  259. proxyApp.Consensus(),
  260. mp,
  261. evidencePool,
  262. blockStore,
  263. )
  264. commit := types.NewCommit(height-1, 0, types.BlockID{}, nil)
  265. block, _, err := blockExec.CreateProposalBlock(
  266. height,
  267. state, commit,
  268. proposerAddr,
  269. )
  270. require.NoError(t, err)
  271. // check that the part set does not exceed the maximum block size
  272. partSet, err := block.MakePartSet(partSize)
  273. require.NoError(t, err)
  274. assert.Less(t, partSet.ByteSize(), int64(maxBytes))
  275. partSetFromHeader := types.NewPartSetFromHeader(partSet.Header())
  276. for partSetFromHeader.Count() < partSetFromHeader.Total() {
  277. added, err := partSetFromHeader.AddPart(partSet.GetPart(int(partSetFromHeader.Count())))
  278. require.NoError(t, err)
  279. require.True(t, added)
  280. }
  281. assert.EqualValues(t, partSetFromHeader.ByteSize(), partSet.ByteSize())
  282. err = blockExec.ValidateBlock(state, block)
  283. assert.NoError(t, err)
  284. }
  285. func TestMaxTxsProposalBlockSize(t *testing.T) {
  286. ctx, cancel := context.WithCancel(context.Background())
  287. defer cancel()
  288. cfg, err := config.ResetTestRoot("node_create_proposal")
  289. require.NoError(t, err)
  290. defer os.RemoveAll(cfg.RootDir)
  291. logger := log.NewTestingLogger(t)
  292. cc := abciclient.NewLocalCreator(kvstore.NewApplication())
  293. proxyApp := proxy.NewAppConns(cc, logger, proxy.NopMetrics())
  294. err = proxyApp.Start(ctx)
  295. require.NoError(t, err)
  296. const height int64 = 1
  297. state, stateDB, _ := state(t, 1, height)
  298. stateStore := sm.NewStore(stateDB)
  299. blockStore := store.NewBlockStore(dbm.NewMemDB())
  300. const maxBytes int64 = 16384
  301. const partSize uint32 = 256
  302. state.ConsensusParams.Block.MaxBytes = maxBytes
  303. proposerAddr, _ := state.Validators.GetByIndex(0)
  304. // Make Mempool
  305. mp := mempool.NewTxMempool(
  306. logger.With("module", "mempool"),
  307. cfg.Mempool,
  308. proxyApp.Mempool(),
  309. state.LastBlockHeight,
  310. )
  311. // fill the mempool with one txs just below the maximum size
  312. txLength := int(types.MaxDataBytesNoEvidence(maxBytes, 1))
  313. tx := tmrand.Bytes(txLength - 4) // to account for the varint
  314. err = mp.CheckTx(ctx, tx, nil, mempool.TxInfo{})
  315. assert.NoError(t, err)
  316. blockExec := sm.NewBlockExecutor(
  317. stateStore,
  318. logger,
  319. proxyApp.Consensus(),
  320. mp,
  321. sm.EmptyEvidencePool{},
  322. blockStore,
  323. )
  324. commit := types.NewCommit(height-1, 0, types.BlockID{}, nil)
  325. block, _, err := blockExec.CreateProposalBlock(
  326. height,
  327. state, commit,
  328. proposerAddr,
  329. )
  330. require.NoError(t, err)
  331. pb, err := block.ToProto()
  332. require.NoError(t, err)
  333. assert.Less(t, int64(pb.Size()), maxBytes)
  334. // check that the part set does not exceed the maximum block size
  335. partSet, err := block.MakePartSet(partSize)
  336. require.NoError(t, err)
  337. assert.EqualValues(t, partSet.ByteSize(), int64(pb.Size()))
  338. }
  339. func TestMaxProposalBlockSize(t *testing.T) {
  340. ctx, cancel := context.WithCancel(context.Background())
  341. defer cancel()
  342. cfg, err := config.ResetTestRoot("node_create_proposal")
  343. require.NoError(t, err)
  344. defer os.RemoveAll(cfg.RootDir)
  345. logger := log.NewTestingLogger(t)
  346. cc := abciclient.NewLocalCreator(kvstore.NewApplication())
  347. proxyApp := proxy.NewAppConns(cc, logger, proxy.NopMetrics())
  348. err = proxyApp.Start(ctx)
  349. require.NoError(t, err)
  350. state, stateDB, _ := state(t, types.MaxVotesCount, int64(1))
  351. stateStore := sm.NewStore(stateDB)
  352. blockStore := store.NewBlockStore(dbm.NewMemDB())
  353. const maxBytes int64 = 1024 * 1024 * 2
  354. state.ConsensusParams.Block.MaxBytes = maxBytes
  355. proposerAddr, _ := state.Validators.GetByIndex(0)
  356. // Make Mempool
  357. mp := mempool.NewTxMempool(
  358. logger.With("module", "mempool"),
  359. cfg.Mempool,
  360. proxyApp.Mempool(),
  361. state.LastBlockHeight,
  362. )
  363. // fill the mempool with one txs just below the maximum size
  364. txLength := int(types.MaxDataBytesNoEvidence(maxBytes, types.MaxVotesCount))
  365. tx := tmrand.Bytes(txLength - 6) // to account for the varint
  366. err = mp.CheckTx(ctx, tx, nil, mempool.TxInfo{})
  367. assert.NoError(t, err)
  368. // now produce more txs than what a normal block can hold with 10 smaller txs
  369. // At the end of the test, only the single big tx should be added
  370. for i := 0; i < 10; i++ {
  371. tx := tmrand.Bytes(10)
  372. err = mp.CheckTx(ctx, tx, nil, mempool.TxInfo{})
  373. assert.NoError(t, err)
  374. }
  375. blockExec := sm.NewBlockExecutor(
  376. stateStore,
  377. logger,
  378. proxyApp.Consensus(),
  379. mp,
  380. sm.EmptyEvidencePool{},
  381. blockStore,
  382. )
  383. blockID := types.BlockID{
  384. Hash: tmhash.Sum([]byte("blockID_hash")),
  385. PartSetHeader: types.PartSetHeader{
  386. Total: math.MaxInt32,
  387. Hash: tmhash.Sum([]byte("blockID_part_set_header_hash")),
  388. },
  389. }
  390. timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
  391. // change state in order to produce the largest accepted header
  392. state.LastBlockID = blockID
  393. state.LastBlockHeight = math.MaxInt64 - 1
  394. state.LastBlockTime = timestamp
  395. state.LastResultsHash = tmhash.Sum([]byte("last_results_hash"))
  396. state.AppHash = tmhash.Sum([]byte("app_hash"))
  397. state.Version.Consensus.Block = math.MaxInt64
  398. state.Version.Consensus.App = math.MaxInt64
  399. maxChainID := ""
  400. for i := 0; i < types.MaxChainIDLen; i++ {
  401. maxChainID += "𠜎"
  402. }
  403. state.ChainID = maxChainID
  404. cs := types.CommitSig{
  405. BlockIDFlag: types.BlockIDFlagNil,
  406. ValidatorAddress: crypto.AddressHash([]byte("validator_address")),
  407. Timestamp: timestamp,
  408. Signature: crypto.CRandBytes(types.MaxSignatureSize),
  409. }
  410. commit := &types.Commit{
  411. Height: math.MaxInt64,
  412. Round: math.MaxInt32,
  413. BlockID: blockID,
  414. }
  415. // add maximum amount of signatures to a single commit
  416. for i := 0; i < types.MaxVotesCount; i++ {
  417. commit.Signatures = append(commit.Signatures, cs)
  418. }
  419. block, partSet, err := blockExec.CreateProposalBlock(
  420. math.MaxInt64,
  421. state, commit,
  422. proposerAddr,
  423. )
  424. require.NoError(t, err)
  425. // this ensures that the header is at max size
  426. block.Header.Time = timestamp
  427. pb, err := block.ToProto()
  428. require.NoError(t, err)
  429. // require that the header and commit be the max possible size
  430. require.Equal(t, int64(pb.Header.Size()), types.MaxHeaderBytes)
  431. require.Equal(t, int64(pb.LastCommit.Size()), types.MaxCommitBytes(types.MaxVotesCount))
  432. // make sure that the block is less than the max possible size
  433. assert.Equal(t, int64(pb.Size()), maxBytes)
  434. // because of the proto overhead we expect the part set bytes to be equal or
  435. // less than the pb block size
  436. assert.LessOrEqual(t, partSet.ByteSize(), int64(pb.Size()))
  437. }
  438. func TestNodeNewSeedNode(t *testing.T) {
  439. cfg, err := config.ResetTestRoot("node_new_node_custom_reactors_test")
  440. require.NoError(t, err)
  441. cfg.Mode = config.ModeSeed
  442. defer os.RemoveAll(cfg.RootDir)
  443. ctx, cancel := context.WithCancel(context.Background())
  444. defer cancel()
  445. nodeKey, err := types.LoadOrGenNodeKey(cfg.NodeKeyFile())
  446. require.NoError(t, err)
  447. logger := log.NewTestingLogger(t)
  448. ns, err := makeSeedNode(ctx,
  449. cfg,
  450. config.DefaultDBProvider,
  451. nodeKey,
  452. defaultGenesisDocProviderFunc(cfg),
  453. logger,
  454. )
  455. t.Cleanup(ns.Wait)
  456. require.NoError(t, err)
  457. n, ok := ns.(*seedNodeImpl)
  458. require.True(t, ok)
  459. err = n.Start(ctx)
  460. require.NoError(t, err)
  461. assert.True(t, n.pexReactor.IsRunning())
  462. cancel()
  463. n.Wait()
  464. assert.False(t, n.pexReactor.IsRunning())
  465. }
  466. func TestNodeSetEventSink(t *testing.T) {
  467. cfg, err := config.ResetTestRoot("node_app_version_test")
  468. require.NoError(t, err)
  469. defer os.RemoveAll(cfg.RootDir)
  470. ctx, cancel := context.WithCancel(context.Background())
  471. defer cancel()
  472. logger := log.NewTestingLogger(t)
  473. setupTest := func(t *testing.T, conf *config.Config) []indexer.EventSink {
  474. eventBus := eventbus.NewDefault(logger.With("module", "events"))
  475. require.NoError(t, eventBus.Start(ctx))
  476. t.Cleanup(eventBus.Wait)
  477. genDoc, err := types.GenesisDocFromFile(cfg.GenesisFile())
  478. require.NoError(t, err)
  479. indexService, eventSinks, err := createAndStartIndexerService(ctx, cfg,
  480. config.DefaultDBProvider, eventBus, logger, genDoc.ChainID,
  481. indexer.NopMetrics())
  482. require.NoError(t, err)
  483. t.Cleanup(indexService.Wait)
  484. return eventSinks
  485. }
  486. cleanup := func(ns service.Service) func() {
  487. return func() {
  488. n, ok := ns.(*nodeImpl)
  489. if !ok {
  490. return
  491. }
  492. if n == nil {
  493. return
  494. }
  495. if !n.IsRunning() {
  496. return
  497. }
  498. cancel()
  499. n.Wait()
  500. }
  501. }
  502. eventSinks := setupTest(t, cfg)
  503. assert.Equal(t, 1, len(eventSinks))
  504. assert.Equal(t, indexer.KV, eventSinks[0].Type())
  505. cfg.TxIndex.Indexer = []string{"null"}
  506. eventSinks = setupTest(t, cfg)
  507. assert.Equal(t, 1, len(eventSinks))
  508. assert.Equal(t, indexer.NULL, eventSinks[0].Type())
  509. cfg.TxIndex.Indexer = []string{"null", "kv"}
  510. eventSinks = setupTest(t, cfg)
  511. assert.Equal(t, 1, len(eventSinks))
  512. assert.Equal(t, indexer.NULL, eventSinks[0].Type())
  513. cfg.TxIndex.Indexer = []string{"kvv"}
  514. ns, err := newDefaultNode(ctx, cfg, logger)
  515. assert.Nil(t, ns)
  516. assert.Contains(t, err.Error(), "unsupported event sink type")
  517. t.Cleanup(cleanup(ns))
  518. cfg.TxIndex.Indexer = []string{}
  519. eventSinks = setupTest(t, cfg)
  520. assert.Equal(t, 1, len(eventSinks))
  521. assert.Equal(t, indexer.NULL, eventSinks[0].Type())
  522. cfg.TxIndex.Indexer = []string{"psql"}
  523. ns, err = newDefaultNode(ctx, cfg, logger)
  524. assert.Nil(t, ns)
  525. assert.Contains(t, err.Error(), "the psql connection settings cannot be empty")
  526. t.Cleanup(cleanup(ns))
  527. // N.B. We can't create a PSQL event sink without starting a postgres
  528. // instance for it to talk to. The indexer service tests exercise that case.
  529. var e = errors.New("found duplicated sinks, please check the tx-index section in the config.toml")
  530. cfg.TxIndex.Indexer = []string{"null", "kv", "Kv"}
  531. ns, err = newDefaultNode(ctx, cfg, logger)
  532. require.Error(t, err)
  533. assert.Contains(t, err.Error(), e.Error())
  534. t.Cleanup(cleanup(ns))
  535. cfg.TxIndex.Indexer = []string{"Null", "kV", "kv", "nUlL"}
  536. ns, err = newDefaultNode(ctx, cfg, logger)
  537. require.Error(t, err)
  538. assert.Contains(t, err.Error(), e.Error())
  539. t.Cleanup(cleanup(ns))
  540. }
  541. func state(t *testing.T, nVals int, height int64) (sm.State, dbm.DB, []types.PrivValidator) {
  542. t.Helper()
  543. privVals := make([]types.PrivValidator, nVals)
  544. vals := make([]types.GenesisValidator, nVals)
  545. for i := 0; i < nVals; i++ {
  546. privVal := types.NewMockPV()
  547. privVals[i] = privVal
  548. vals[i] = types.GenesisValidator{
  549. Address: privVal.PrivKey.PubKey().Address(),
  550. PubKey: privVal.PrivKey.PubKey(),
  551. Power: 1000,
  552. Name: fmt.Sprintf("test%d", i),
  553. }
  554. }
  555. s, _ := sm.MakeGenesisState(&types.GenesisDoc{
  556. ChainID: "test-chain",
  557. Validators: vals,
  558. AppHash: nil,
  559. })
  560. // save validators to db for 2 heights
  561. stateDB := dbm.NewMemDB()
  562. t.Cleanup(func() { require.NoError(t, stateDB.Close()) })
  563. stateStore := sm.NewStore(stateDB)
  564. require.NoError(t, stateStore.Save(s))
  565. for i := 1; i < int(height); i++ {
  566. s.LastBlockHeight++
  567. s.LastValidators = s.Validators.Copy()
  568. require.NoError(t, stateStore.Save(s))
  569. }
  570. return s, stateDB, privVals
  571. }
  572. func TestLoadStateFromGenesis(t *testing.T) {
  573. ctx, cancel := context.WithCancel(context.Background())
  574. defer cancel()
  575. _ = loadStatefromGenesis(ctx, t)
  576. }
  577. func loadStatefromGenesis(ctx context.Context, t *testing.T) sm.State {
  578. t.Helper()
  579. stateDB := dbm.NewMemDB()
  580. stateStore := sm.NewStore(stateDB)
  581. cfg, err := config.ResetTestRoot("load_state_from_genesis")
  582. require.NoError(t, err)
  583. loadedState, err := stateStore.Load()
  584. require.NoError(t, err)
  585. require.True(t, loadedState.IsEmpty())
  586. genDoc, _ := factory.RandGenesisDoc(ctx, t, cfg, 0, false, 10)
  587. state, err := loadStateFromDBOrGenesisDocProvider(
  588. stateStore,
  589. genDoc,
  590. )
  591. require.NoError(t, err)
  592. require.NotNil(t, state)
  593. return state
  594. }