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.

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