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.

742 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.NewNopLogger()
  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. t.Cleanup(leaktest.CheckTimeout(t, time.Second))
  86. return n
  87. }
  88. func TestNodeDelayedStart(t *testing.T) {
  89. cfg, err := config.ResetTestRoot("node_delayed_start_test")
  90. require.NoError(t, err)
  91. defer os.RemoveAll(cfg.RootDir)
  92. now := tmtime.Now()
  93. ctx, cancel := context.WithCancel(context.Background())
  94. defer cancel()
  95. logger := log.NewNopLogger()
  96. // create & start node
  97. n := getTestNode(ctx, t, cfg, logger)
  98. n.GenesisDoc().GenesisTime = now.Add(2 * time.Second)
  99. require.NoError(t, n.Start(ctx))
  100. startTime := tmtime.Now()
  101. assert.Equal(t, true, startTime.After(n.GenesisDoc().GenesisTime))
  102. }
  103. func TestNodeSetAppVersion(t *testing.T) {
  104. cfg, err := config.ResetTestRoot("node_app_version_test")
  105. require.NoError(t, err)
  106. defer os.RemoveAll(cfg.RootDir)
  107. ctx, cancel := context.WithCancel(context.Background())
  108. defer cancel()
  109. logger := log.NewNopLogger()
  110. // create node
  111. n := getTestNode(ctx, t, cfg, logger)
  112. // default config uses the kvstore app
  113. appVersion := kvstore.ProtocolVersion
  114. // check version is set in state
  115. state, err := n.stateStore.Load()
  116. require.NoError(t, err)
  117. assert.Equal(t, state.Version.Consensus.App, appVersion)
  118. // check version is set in node info
  119. assert.Equal(t, n.nodeInfo.ProtocolVersion.App, appVersion)
  120. }
  121. func TestNodeSetPrivValTCP(t *testing.T) {
  122. addr := "tcp://" + testFreeAddr(t)
  123. t.Cleanup(leaktest.Check(t))
  124. ctx, cancel := context.WithCancel(context.Background())
  125. defer cancel()
  126. logger := log.NewNopLogger()
  127. cfg, err := config.ResetTestRoot("node_priv_val_tcp_test")
  128. require.NoError(t, err)
  129. defer os.RemoveAll(cfg.RootDir)
  130. cfg.PrivValidator.ListenAddr = addr
  131. dialer := privval.DialTCPFn(addr, 100*time.Millisecond, ed25519.GenPrivKey())
  132. dialerEndpoint := privval.NewSignerDialerEndpoint(logger, dialer)
  133. privval.SignerDialerEndpointTimeoutReadWrite(100 * time.Millisecond)(dialerEndpoint)
  134. signerServer := privval.NewSignerServer(
  135. dialerEndpoint,
  136. cfg.ChainID(),
  137. types.NewMockPV(),
  138. )
  139. go func() {
  140. err := signerServer.Start(ctx)
  141. require.NoError(t, err)
  142. }()
  143. defer signerServer.Stop() //nolint:errcheck // ignore for tests
  144. genDoc, err := defaultGenesisDocProviderFunc(cfg)()
  145. require.NoError(t, err)
  146. pval, err := createPrivval(ctx, logger, cfg, genDoc, nil)
  147. require.NoError(t, err)
  148. assert.IsType(t, &privval.RetrySignerClient{}, pval)
  149. }
  150. // address without a protocol must result in error
  151. func TestPrivValidatorListenAddrNoProtocol(t *testing.T) {
  152. ctx, cancel := context.WithCancel(context.Background())
  153. defer cancel()
  154. addrNoPrefix := testFreeAddr(t)
  155. cfg, err := config.ResetTestRoot("node_priv_val_tcp_test")
  156. require.NoError(t, err)
  157. defer os.RemoveAll(cfg.RootDir)
  158. cfg.PrivValidator.ListenAddr = addrNoPrefix
  159. logger := log.NewNopLogger()
  160. n, err := newDefaultNode(ctx, cfg, logger)
  161. assert.Error(t, err)
  162. if n != nil && n.IsRunning() {
  163. cancel()
  164. n.Wait()
  165. }
  166. }
  167. func TestNodeSetPrivValIPC(t *testing.T) {
  168. tmpfile := "/tmp/kms." + tmrand.Str(6) + ".sock"
  169. defer os.Remove(tmpfile) // clean up
  170. ctx, cancel := context.WithCancel(context.Background())
  171. defer cancel()
  172. cfg, err := config.ResetTestRoot("node_priv_val_tcp_test")
  173. require.NoError(t, err)
  174. defer os.RemoveAll(cfg.RootDir)
  175. cfg.PrivValidator.ListenAddr = "unix://" + tmpfile
  176. logger := log.NewNopLogger()
  177. dialer := privval.DialUnixFn(tmpfile)
  178. dialerEndpoint := privval.NewSignerDialerEndpoint(logger, dialer)
  179. privval.SignerDialerEndpointTimeoutReadWrite(100 * time.Millisecond)(dialerEndpoint)
  180. pvsc := privval.NewSignerServer(
  181. dialerEndpoint,
  182. cfg.ChainID(),
  183. types.NewMockPV(),
  184. )
  185. go func() {
  186. err := pvsc.Start(ctx)
  187. require.NoError(t, err)
  188. }()
  189. defer pvsc.Stop() //nolint:errcheck // ignore for tests
  190. genDoc, err := defaultGenesisDocProviderFunc(cfg)()
  191. require.NoError(t, err)
  192. pval, err := createPrivval(ctx, logger, cfg, genDoc, nil)
  193. require.NoError(t, err)
  194. assert.IsType(t, &privval.RetrySignerClient{}, pval)
  195. }
  196. // testFreeAddr claims a free port so we don't block on listener being ready.
  197. func testFreeAddr(t *testing.T) string {
  198. ln, err := net.Listen("tcp", "127.0.0.1:0")
  199. require.NoError(t, err)
  200. defer ln.Close()
  201. return fmt.Sprintf("127.0.0.1:%d", ln.Addr().(*net.TCPAddr).Port)
  202. }
  203. // create a proposal block using real and full
  204. // mempool and evidence pool and validate it.
  205. func TestCreateProposalBlock(t *testing.T) {
  206. ctx, cancel := context.WithCancel(context.Background())
  207. defer cancel()
  208. cfg, err := config.ResetTestRoot("node_create_proposal")
  209. require.NoError(t, err)
  210. defer os.RemoveAll(cfg.RootDir)
  211. logger := log.NewNopLogger()
  212. cc := abciclient.NewLocalCreator(kvstore.NewApplication())
  213. proxyApp := proxy.NewAppConns(cc, logger, proxy.NopMetrics())
  214. err = proxyApp.Start(ctx)
  215. require.NoError(t, err)
  216. const height int64 = 1
  217. state, stateDB, privVals := state(t, 1, height)
  218. stateStore := sm.NewStore(stateDB)
  219. maxBytes := 16384
  220. const partSize uint32 = 256
  221. maxEvidenceBytes := int64(maxBytes / 2)
  222. state.ConsensusParams.Block.MaxBytes = int64(maxBytes)
  223. state.ConsensusParams.Evidence.MaxBytes = maxEvidenceBytes
  224. proposerAddr, _ := state.Validators.GetByIndex(0)
  225. mp := mempool.NewTxMempool(
  226. logger.With("module", "mempool"),
  227. cfg.Mempool,
  228. proxyApp.Mempool(),
  229. state.LastBlockHeight,
  230. )
  231. // Make EvidencePool
  232. evidenceDB := dbm.NewMemDB()
  233. blockStore := store.NewBlockStore(dbm.NewMemDB())
  234. evidencePool, err := evidence.NewPool(logger, evidenceDB, stateStore, blockStore)
  235. require.NoError(t, err)
  236. // fill the evidence pool with more evidence
  237. // than can fit in a block
  238. var currentBytes int64
  239. for currentBytes <= maxEvidenceBytes {
  240. ev, err := types.NewMockDuplicateVoteEvidenceWithValidator(ctx, height, time.Now(), privVals[0], "test-chain")
  241. require.NoError(t, err)
  242. currentBytes += int64(len(ev.Bytes()))
  243. evidencePool.ReportConflictingVotes(ev.VoteA, ev.VoteB)
  244. }
  245. evList, size := evidencePool.PendingEvidence(state.ConsensusParams.Evidence.MaxBytes)
  246. require.Less(t, size, state.ConsensusParams.Evidence.MaxBytes+1)
  247. evData := &types.EvidenceData{Evidence: evList}
  248. require.EqualValues(t, size, evData.ByteSize())
  249. // fill the mempool with more txs
  250. // than can fit in a block
  251. txLength := 100
  252. for i := 0; i <= maxBytes/txLength; i++ {
  253. tx := tmrand.Bytes(txLength)
  254. err := mp.CheckTx(ctx, tx, nil, mempool.TxInfo{})
  255. assert.NoError(t, err)
  256. }
  257. blockExec := sm.NewBlockExecutor(
  258. stateStore,
  259. logger,
  260. proxyApp.Consensus(),
  261. mp,
  262. evidencePool,
  263. blockStore,
  264. )
  265. commit := types.NewCommit(height-1, 0, types.BlockID{}, nil)
  266. block, _, err := blockExec.CreateProposalBlock(
  267. height,
  268. state, commit,
  269. proposerAddr,
  270. )
  271. require.NoError(t, err)
  272. // check that the part set does not exceed the maximum block size
  273. partSet, err := block.MakePartSet(partSize)
  274. require.NoError(t, err)
  275. assert.Less(t, partSet.ByteSize(), int64(maxBytes))
  276. partSetFromHeader := types.NewPartSetFromHeader(partSet.Header())
  277. for partSetFromHeader.Count() < partSetFromHeader.Total() {
  278. added, err := partSetFromHeader.AddPart(partSet.GetPart(int(partSetFromHeader.Count())))
  279. require.NoError(t, err)
  280. require.True(t, added)
  281. }
  282. assert.EqualValues(t, partSetFromHeader.ByteSize(), partSet.ByteSize())
  283. err = blockExec.ValidateBlock(state, block)
  284. assert.NoError(t, err)
  285. }
  286. func TestMaxTxsProposalBlockSize(t *testing.T) {
  287. ctx, cancel := context.WithCancel(context.Background())
  288. defer cancel()
  289. cfg, err := config.ResetTestRoot("node_create_proposal")
  290. require.NoError(t, err)
  291. defer os.RemoveAll(cfg.RootDir)
  292. logger := log.NewNopLogger()
  293. cc := abciclient.NewLocalCreator(kvstore.NewApplication())
  294. proxyApp := proxy.NewAppConns(cc, logger, proxy.NopMetrics())
  295. err = proxyApp.Start(ctx)
  296. require.NoError(t, err)
  297. const height int64 = 1
  298. state, stateDB, _ := state(t, 1, height)
  299. stateStore := sm.NewStore(stateDB)
  300. blockStore := store.NewBlockStore(dbm.NewMemDB())
  301. const maxBytes int64 = 16384
  302. const partSize uint32 = 256
  303. state.ConsensusParams.Block.MaxBytes = maxBytes
  304. proposerAddr, _ := state.Validators.GetByIndex(0)
  305. // Make Mempool
  306. mp := mempool.NewTxMempool(
  307. logger.With("module", "mempool"),
  308. cfg.Mempool,
  309. proxyApp.Mempool(),
  310. state.LastBlockHeight,
  311. )
  312. // fill the mempool with one txs just below the maximum size
  313. txLength := int(types.MaxDataBytesNoEvidence(maxBytes, 1))
  314. tx := tmrand.Bytes(txLength - 4) // to account for the varint
  315. err = mp.CheckTx(ctx, tx, nil, mempool.TxInfo{})
  316. assert.NoError(t, err)
  317. blockExec := sm.NewBlockExecutor(
  318. stateStore,
  319. logger,
  320. proxyApp.Consensus(),
  321. mp,
  322. sm.EmptyEvidencePool{},
  323. blockStore,
  324. )
  325. commit := types.NewCommit(height-1, 0, types.BlockID{}, nil)
  326. block, _, err := blockExec.CreateProposalBlock(
  327. height,
  328. state, commit,
  329. proposerAddr,
  330. )
  331. require.NoError(t, err)
  332. pb, err := block.ToProto()
  333. require.NoError(t, err)
  334. assert.Less(t, int64(pb.Size()), maxBytes)
  335. // check that the part set does not exceed the maximum block size
  336. partSet, err := block.MakePartSet(partSize)
  337. require.NoError(t, err)
  338. assert.EqualValues(t, partSet.ByteSize(), int64(pb.Size()))
  339. }
  340. func TestMaxProposalBlockSize(t *testing.T) {
  341. ctx, cancel := context.WithCancel(context.Background())
  342. defer cancel()
  343. cfg, err := config.ResetTestRoot("node_create_proposal")
  344. require.NoError(t, err)
  345. defer os.RemoveAll(cfg.RootDir)
  346. logger := log.NewNopLogger()
  347. cc := abciclient.NewLocalCreator(kvstore.NewApplication())
  348. proxyApp := proxy.NewAppConns(cc, logger, proxy.NopMetrics())
  349. err = proxyApp.Start(ctx)
  350. require.NoError(t, err)
  351. state, stateDB, _ := state(t, types.MaxVotesCount, int64(1))
  352. stateStore := sm.NewStore(stateDB)
  353. blockStore := store.NewBlockStore(dbm.NewMemDB())
  354. const maxBytes int64 = 1024 * 1024 * 2
  355. state.ConsensusParams.Block.MaxBytes = maxBytes
  356. proposerAddr, _ := state.Validators.GetByIndex(0)
  357. // Make Mempool
  358. mp := mempool.NewTxMempool(
  359. logger.With("module", "mempool"),
  360. cfg.Mempool,
  361. proxyApp.Mempool(),
  362. state.LastBlockHeight,
  363. )
  364. // fill the mempool with one txs just below the maximum size
  365. txLength := int(types.MaxDataBytesNoEvidence(maxBytes, types.MaxVotesCount))
  366. tx := tmrand.Bytes(txLength - 6) // to account for the varint
  367. err = mp.CheckTx(ctx, tx, nil, mempool.TxInfo{})
  368. assert.NoError(t, err)
  369. // now produce more txs than what a normal block can hold with 10 smaller txs
  370. // At the end of the test, only the single big tx should be added
  371. for i := 0; i < 10; i++ {
  372. tx := tmrand.Bytes(10)
  373. err = mp.CheckTx(ctx, tx, nil, mempool.TxInfo{})
  374. assert.NoError(t, err)
  375. }
  376. blockExec := sm.NewBlockExecutor(
  377. stateStore,
  378. logger,
  379. proxyApp.Consensus(),
  380. mp,
  381. sm.EmptyEvidencePool{},
  382. blockStore,
  383. )
  384. blockID := types.BlockID{
  385. Hash: tmhash.Sum([]byte("blockID_hash")),
  386. PartSetHeader: types.PartSetHeader{
  387. Total: math.MaxInt32,
  388. Hash: tmhash.Sum([]byte("blockID_part_set_header_hash")),
  389. },
  390. }
  391. timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
  392. // change state in order to produce the largest accepted header
  393. state.LastBlockID = blockID
  394. state.LastBlockHeight = math.MaxInt64 - 1
  395. state.LastBlockTime = timestamp
  396. state.LastResultsHash = tmhash.Sum([]byte("last_results_hash"))
  397. state.AppHash = tmhash.Sum([]byte("app_hash"))
  398. state.Version.Consensus.Block = math.MaxInt64
  399. state.Version.Consensus.App = math.MaxInt64
  400. maxChainID := ""
  401. for i := 0; i < types.MaxChainIDLen; i++ {
  402. maxChainID += "𠜎"
  403. }
  404. state.ChainID = maxChainID
  405. cs := types.CommitSig{
  406. BlockIDFlag: types.BlockIDFlagNil,
  407. ValidatorAddress: crypto.AddressHash([]byte("validator_address")),
  408. Timestamp: timestamp,
  409. Signature: crypto.CRandBytes(types.MaxSignatureSize),
  410. }
  411. commit := &types.Commit{
  412. Height: math.MaxInt64,
  413. Round: math.MaxInt32,
  414. BlockID: blockID,
  415. }
  416. // add maximum amount of signatures to a single commit
  417. for i := 0; i < types.MaxVotesCount; i++ {
  418. commit.Signatures = append(commit.Signatures, cs)
  419. }
  420. block, partSet, err := blockExec.CreateProposalBlock(
  421. math.MaxInt64,
  422. state, commit,
  423. proposerAddr,
  424. )
  425. require.NoError(t, err)
  426. // this ensures that the header is at max size
  427. block.Header.Time = timestamp
  428. pb, err := block.ToProto()
  429. require.NoError(t, err)
  430. // require that the header and commit be the max possible size
  431. require.Equal(t, int64(pb.Header.Size()), types.MaxHeaderBytes)
  432. require.Equal(t, int64(pb.LastCommit.Size()), types.MaxCommitBytes(types.MaxVotesCount))
  433. // make sure that the block is less than the max possible size
  434. assert.Equal(t, int64(pb.Size()), maxBytes)
  435. // because of the proto overhead we expect the part set bytes to be equal or
  436. // less than the pb block size
  437. assert.LessOrEqual(t, partSet.ByteSize(), int64(pb.Size()))
  438. }
  439. func TestNodeNewSeedNode(t *testing.T) {
  440. cfg, err := config.ResetTestRoot("node_new_node_custom_reactors_test")
  441. require.NoError(t, err)
  442. cfg.Mode = config.ModeSeed
  443. defer os.RemoveAll(cfg.RootDir)
  444. ctx, cancel := context.WithCancel(context.Background())
  445. defer cancel()
  446. nodeKey, err := types.LoadOrGenNodeKey(cfg.NodeKeyFile())
  447. require.NoError(t, err)
  448. logger := log.NewNopLogger()
  449. ns, err := makeSeedNode(ctx,
  450. cfg,
  451. config.DefaultDBProvider,
  452. nodeKey,
  453. defaultGenesisDocProviderFunc(cfg),
  454. logger,
  455. )
  456. t.Cleanup(ns.Wait)
  457. require.NoError(t, err)
  458. n, ok := ns.(*seedNodeImpl)
  459. require.True(t, ok)
  460. err = n.Start(ctx)
  461. require.NoError(t, err)
  462. assert.True(t, n.pexReactor.IsRunning())
  463. cancel()
  464. n.Wait()
  465. assert.False(t, n.pexReactor.IsRunning())
  466. }
  467. func TestNodeSetEventSink(t *testing.T) {
  468. cfg, err := config.ResetTestRoot("node_app_version_test")
  469. require.NoError(t, err)
  470. defer os.RemoveAll(cfg.RootDir)
  471. ctx, cancel := context.WithCancel(context.Background())
  472. defer cancel()
  473. logger := log.NewNopLogger()
  474. setupTest := func(t *testing.T, conf *config.Config) []indexer.EventSink {
  475. eventBus := eventbus.NewDefault(logger.With("module", "events"))
  476. require.NoError(t, eventBus.Start(ctx))
  477. t.Cleanup(eventBus.Wait)
  478. genDoc, err := types.GenesisDocFromFile(cfg.GenesisFile())
  479. require.NoError(t, err)
  480. indexService, eventSinks, err := createAndStartIndexerService(ctx, cfg,
  481. config.DefaultDBProvider, eventBus, logger, genDoc.ChainID,
  482. indexer.NopMetrics())
  483. require.NoError(t, err)
  484. t.Cleanup(indexService.Wait)
  485. return eventSinks
  486. }
  487. cleanup := func(ns service.Service) func() {
  488. return func() {
  489. n, ok := ns.(*nodeImpl)
  490. if !ok {
  491. return
  492. }
  493. if n == nil {
  494. return
  495. }
  496. if !n.IsRunning() {
  497. return
  498. }
  499. cancel()
  500. n.Wait()
  501. }
  502. }
  503. eventSinks := setupTest(t, cfg)
  504. assert.Equal(t, 1, len(eventSinks))
  505. assert.Equal(t, indexer.KV, eventSinks[0].Type())
  506. cfg.TxIndex.Indexer = []string{"null"}
  507. eventSinks = setupTest(t, cfg)
  508. assert.Equal(t, 1, len(eventSinks))
  509. assert.Equal(t, indexer.NULL, eventSinks[0].Type())
  510. cfg.TxIndex.Indexer = []string{"null", "kv"}
  511. eventSinks = setupTest(t, cfg)
  512. assert.Equal(t, 1, len(eventSinks))
  513. assert.Equal(t, indexer.NULL, eventSinks[0].Type())
  514. cfg.TxIndex.Indexer = []string{"kvv"}
  515. ns, err := newDefaultNode(ctx, cfg, logger)
  516. assert.Nil(t, ns)
  517. assert.Contains(t, err.Error(), "unsupported event sink type")
  518. t.Cleanup(cleanup(ns))
  519. cfg.TxIndex.Indexer = []string{}
  520. eventSinks = setupTest(t, cfg)
  521. assert.Equal(t, 1, len(eventSinks))
  522. assert.Equal(t, indexer.NULL, eventSinks[0].Type())
  523. cfg.TxIndex.Indexer = []string{"psql"}
  524. ns, err = newDefaultNode(ctx, cfg, logger)
  525. assert.Nil(t, ns)
  526. assert.Contains(t, err.Error(), "the psql connection settings cannot be empty")
  527. t.Cleanup(cleanup(ns))
  528. // N.B. We can't create a PSQL event sink without starting a postgres
  529. // instance for it to talk to. The indexer service tests exercise that case.
  530. var e = errors.New("found duplicated sinks, please check the tx-index section in the config.toml")
  531. cfg.TxIndex.Indexer = []string{"null", "kv", "Kv"}
  532. ns, err = newDefaultNode(ctx, cfg, logger)
  533. require.Error(t, err)
  534. assert.Contains(t, err.Error(), e.Error())
  535. t.Cleanup(cleanup(ns))
  536. cfg.TxIndex.Indexer = []string{"Null", "kV", "kv", "nUlL"}
  537. ns, err = newDefaultNode(ctx, cfg, logger)
  538. require.Error(t, err)
  539. assert.Contains(t, err.Error(), e.Error())
  540. t.Cleanup(cleanup(ns))
  541. }
  542. func state(t *testing.T, nVals int, height int64) (sm.State, dbm.DB, []types.PrivValidator) {
  543. t.Helper()
  544. privVals := make([]types.PrivValidator, nVals)
  545. vals := make([]types.GenesisValidator, nVals)
  546. for i := 0; i < nVals; i++ {
  547. privVal := types.NewMockPV()
  548. privVals[i] = privVal
  549. vals[i] = types.GenesisValidator{
  550. Address: privVal.PrivKey.PubKey().Address(),
  551. PubKey: privVal.PrivKey.PubKey(),
  552. Power: 1000,
  553. Name: fmt.Sprintf("test%d", i),
  554. }
  555. }
  556. s, _ := sm.MakeGenesisState(&types.GenesisDoc{
  557. ChainID: "test-chain",
  558. Validators: vals,
  559. AppHash: nil,
  560. })
  561. // save validators to db for 2 heights
  562. stateDB := dbm.NewMemDB()
  563. t.Cleanup(func() { require.NoError(t, stateDB.Close()) })
  564. stateStore := sm.NewStore(stateDB)
  565. require.NoError(t, stateStore.Save(s))
  566. for i := 1; i < int(height); i++ {
  567. s.LastBlockHeight++
  568. s.LastValidators = s.Validators.Copy()
  569. require.NoError(t, stateStore.Save(s))
  570. }
  571. return s, stateDB, privVals
  572. }
  573. func TestLoadStateFromGenesis(t *testing.T) {
  574. ctx, cancel := context.WithCancel(context.Background())
  575. defer cancel()
  576. _ = loadStatefromGenesis(ctx, t)
  577. }
  578. func loadStatefromGenesis(ctx context.Context, t *testing.T) sm.State {
  579. t.Helper()
  580. stateDB := dbm.NewMemDB()
  581. stateStore := sm.NewStore(stateDB)
  582. cfg, err := config.ResetTestRoot("load_state_from_genesis")
  583. require.NoError(t, err)
  584. loadedState, err := stateStore.Load()
  585. require.NoError(t, err)
  586. require.True(t, loadedState.IsEmpty())
  587. valSet, _ := factory.ValidatorSet(ctx, t, 0, 10)
  588. genDoc := factory.GenesisDoc(cfg, time.Now(), valSet.Validators, nil)
  589. state, err := loadStateFromDBOrGenesisDocProvider(
  590. stateStore,
  591. genDoc,
  592. )
  593. require.NoError(t, err)
  594. require.NotNil(t, state)
  595. return state
  596. }