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.

912 lines
28 KiB

rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
rpc/test: wait for mempool CheckTx callback (#4908) Fixes race conditions causing the following test failures: ``` === RUN TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:342: Error Trace: rpc_test.go:342 Error: Not equal: expected: 1 actual : 0 Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:343: Error Trace: rpc_test.go:343 Error: Not equal: expected: 1 actual : 0 Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:345: Error Trace: rpc_test.go:345 Error: Not equal: expected: types.Txs{types.Tx{0x39, 0x44, 0x4d, 0x6c, 0x4b, 0x66, 0x46, 0x78, 0x3d, 0x45, 0x33, 0x33, 0x68, 0x47, 0x6e, 0x79, 0x58}} actual : types.Txs(nil) Diff: --- Expected +++ Actual @@ -1,4 +1,2 @@ -(types.Txs) (len=1) { - (types.Tx) (len=17) Tx{39444D6C4B6646783D45333368476E7958} -} +(types.Txs) <nil> Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:342: Error Trace: rpc_test.go:342 Error: Not equal: expected: 1 actual : 0 Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:343: Error Trace: rpc_test.go:343 Error: Not equal: expected: 1 actual : 0 Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:345: Error Trace: rpc_test.go:345 Error: Not equal: expected: types.Txs{types.Tx{0x39, 0x44, 0x4d, 0x6c, 0x4b, 0x66, 0x46, 0x78, 0x3d, 0x45, 0x33, 0x33, 0x68, 0x47, 0x6e, 0x79, 0x58}} actual : types.Txs{} Diff: --- Expected +++ Actual @@ -1,3 +1,2 @@ -(types.Txs) (len=1) { - (types.Tx) (len=17) Tx{39444D6C4B6646783D45333368476E7958} +(types.Txs) { } Test: TestUnconfirmedTxs --- FAIL: TestUnconfirmedTxs (0.20s) === RUN TestNumUnconfirmedTxs TestNumUnconfirmedTxs: rpc_test.go:364: Error Trace: rpc_test.go:364 Error: Not equal: expected: 1 actual : 0 Test: TestNumUnconfirmedTxs TestNumUnconfirmedTxs: rpc_test.go:365: Error Trace: rpc_test.go:365 Error: Not equal: expected: 1 actual : 0 Test: TestNumUnconfirmedTxs TestNumUnconfirmedTxs: rpc_test.go:364: Error Trace: rpc_test.go:364 Error: Not equal: expected: 1 actual : 0 Test: TestNumUnconfirmedTxs TestNumUnconfirmedTxs: rpc_test.go:365: Error Trace: rpc_test.go:365 Error: Not equal: expected: 1 actual : 0 Test: TestNumUnconfirmedTxs --- FAIL: TestNumUnconfirmedTxs (0.09s) ```
4 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
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
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
rpc/lib/client & server: try to conform to JSON-RPC 2.0 spec (#4141) https://www.jsonrpc.org/specification What is done in this PR: JSONRPCClient: validate that Response.ID matches Request.ID I wanted to do the same for the WSClient, but since we're sending events as responses, not notifications, checking IDs would require storing them in memory indefinitely (and we won't be able to remove them upon client unsubscribing because ID is different then). Request.ID is now optional. Notification is a Request without an ID. Previously "" or 0 were considered as notifications Remove #event suffix from ID from an event response (partially fixes #2949) ID must be either string, int or null AND must be equal to request's ID. Now, because we've implemented events as responses, WS clients are tripping when they see Response.ID("0#event") != Request.ID("0"). Implementing events as requests would require a lot of time (~ 2 days to completely rewrite WS client and server) generate unique ID for each request switch to integer IDs instead of "json-client-XYZ" id=0 method=/subscribe id=0 result=... id=1 method=/abci_query id=1 result=... > send events (resulting from /subscribe) as requests+notifications (not responses) this will require a lot of work. probably not worth it * rpc: generate an unique ID for each request in conformance with JSON-RPC spec * WSClient: check for unsolicited responses * fix golangci warnings * save commit * fix errors * remove ID from responses from subscribe Refs #2949 * clients are safe for concurrent access * tm-bench: switch to int ID * fixes after my own review * comment out sentIDs in WSClient see commit body for the reason * remove body.Close it will be closed automatically * stop ws connection outside of write/read routines also, use t.Rate in tm-bench indexer when calculating ID fix gocritic issues * update swagger.yaml * Apply suggestions from code review * fix stylecheck and golint linter warnings * update changelog * update changelog2
5 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
2 years ago
abci: Synchronize FinalizeBlock with the updated specification (#7983) This change set implements the most recent version of `FinalizeBlock`. # What does this change actually contain? * This change set is rather large but fear not! The majority of the files touched and changes are renaming `ResponseDeliverTx` to `ExecTxResult`. This should be a pretty inoffensive change since they're effectively the same type but with a different name. * The `execBlockOnProxyApp` was totally removed since it served as just a wrapper around the logic that is now mostly encapsulated within `FinalizeBlock` * The `updateState` helper function has been made a public method on `State`. It was being exposed as a shim through the testing infrastructure, so this seemed innocuous. * Tests already existed to ensure that the application received the `ByzantineValidators` and the `ValidatorUpdates`, but one was fixed up to ensure that `LastCommitInfo` was being sent across. * Tests were removed from the `psql` indexer that seemed to search for an event in the indexer that was not being created. # Questions for reviewers * We store this [ABCIResponses](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/proto/tendermint/state/types.pb.go#L37) type in the data base as the block results. This type has changed since v0.35 to contain the `FinalizeBlock` response. I'm wondering if we need to do any shimming to keep the old data retrieveable? * Similarly, this change is exposed via the RPC through [ResultBlockResults](https://github.com/tendermint/tendermint/blob/5721a13ab1f4479f9807f449f0bf5c536b9a05f2/rpc/coretypes/responses.go#L69) changing. Should we somehow shim or notify for this change? closes: #7658
2 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
rpc/test: wait for mempool CheckTx callback (#4908) Fixes race conditions causing the following test failures: ``` === RUN TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:342: Error Trace: rpc_test.go:342 Error: Not equal: expected: 1 actual : 0 Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:343: Error Trace: rpc_test.go:343 Error: Not equal: expected: 1 actual : 0 Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:345: Error Trace: rpc_test.go:345 Error: Not equal: expected: types.Txs{types.Tx{0x39, 0x44, 0x4d, 0x6c, 0x4b, 0x66, 0x46, 0x78, 0x3d, 0x45, 0x33, 0x33, 0x68, 0x47, 0x6e, 0x79, 0x58}} actual : types.Txs(nil) Diff: --- Expected +++ Actual @@ -1,4 +1,2 @@ -(types.Txs) (len=1) { - (types.Tx) (len=17) Tx{39444D6C4B6646783D45333368476E7958} -} +(types.Txs) <nil> Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:342: Error Trace: rpc_test.go:342 Error: Not equal: expected: 1 actual : 0 Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:343: Error Trace: rpc_test.go:343 Error: Not equal: expected: 1 actual : 0 Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:345: Error Trace: rpc_test.go:345 Error: Not equal: expected: types.Txs{types.Tx{0x39, 0x44, 0x4d, 0x6c, 0x4b, 0x66, 0x46, 0x78, 0x3d, 0x45, 0x33, 0x33, 0x68, 0x47, 0x6e, 0x79, 0x58}} actual : types.Txs{} Diff: --- Expected +++ Actual @@ -1,3 +1,2 @@ -(types.Txs) (len=1) { - (types.Tx) (len=17) Tx{39444D6C4B6646783D45333368476E7958} +(types.Txs) { } Test: TestUnconfirmedTxs --- FAIL: TestUnconfirmedTxs (0.20s) === RUN TestNumUnconfirmedTxs TestNumUnconfirmedTxs: rpc_test.go:364: Error Trace: rpc_test.go:364 Error: Not equal: expected: 1 actual : 0 Test: TestNumUnconfirmedTxs TestNumUnconfirmedTxs: rpc_test.go:365: Error Trace: rpc_test.go:365 Error: Not equal: expected: 1 actual : 0 Test: TestNumUnconfirmedTxs TestNumUnconfirmedTxs: rpc_test.go:364: Error Trace: rpc_test.go:364 Error: Not equal: expected: 1 actual : 0 Test: TestNumUnconfirmedTxs TestNumUnconfirmedTxs: rpc_test.go:365: Error Trace: rpc_test.go:365 Error: Not equal: expected: 1 actual : 0 Test: TestNumUnconfirmedTxs --- FAIL: TestNumUnconfirmedTxs (0.09s) ```
4 years ago
rpc/test: wait for mempool CheckTx callback (#4908) Fixes race conditions causing the following test failures: ``` === RUN TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:342: Error Trace: rpc_test.go:342 Error: Not equal: expected: 1 actual : 0 Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:343: Error Trace: rpc_test.go:343 Error: Not equal: expected: 1 actual : 0 Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:345: Error Trace: rpc_test.go:345 Error: Not equal: expected: types.Txs{types.Tx{0x39, 0x44, 0x4d, 0x6c, 0x4b, 0x66, 0x46, 0x78, 0x3d, 0x45, 0x33, 0x33, 0x68, 0x47, 0x6e, 0x79, 0x58}} actual : types.Txs(nil) Diff: --- Expected +++ Actual @@ -1,4 +1,2 @@ -(types.Txs) (len=1) { - (types.Tx) (len=17) Tx{39444D6C4B6646783D45333368476E7958} -} +(types.Txs) <nil> Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:342: Error Trace: rpc_test.go:342 Error: Not equal: expected: 1 actual : 0 Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:343: Error Trace: rpc_test.go:343 Error: Not equal: expected: 1 actual : 0 Test: TestUnconfirmedTxs TestUnconfirmedTxs: rpc_test.go:345: Error Trace: rpc_test.go:345 Error: Not equal: expected: types.Txs{types.Tx{0x39, 0x44, 0x4d, 0x6c, 0x4b, 0x66, 0x46, 0x78, 0x3d, 0x45, 0x33, 0x33, 0x68, 0x47, 0x6e, 0x79, 0x58}} actual : types.Txs{} Diff: --- Expected +++ Actual @@ -1,3 +1,2 @@ -(types.Txs) (len=1) { - (types.Tx) (len=17) Tx{39444D6C4B6646783D45333368476E7958} +(types.Txs) { } Test: TestUnconfirmedTxs --- FAIL: TestUnconfirmedTxs (0.20s) === RUN TestNumUnconfirmedTxs TestNumUnconfirmedTxs: rpc_test.go:364: Error Trace: rpc_test.go:364 Error: Not equal: expected: 1 actual : 0 Test: TestNumUnconfirmedTxs TestNumUnconfirmedTxs: rpc_test.go:365: Error Trace: rpc_test.go:365 Error: Not equal: expected: 1 actual : 0 Test: TestNumUnconfirmedTxs TestNumUnconfirmedTxs: rpc_test.go:364: Error Trace: rpc_test.go:364 Error: Not equal: expected: 1 actual : 0 Test: TestNumUnconfirmedTxs TestNumUnconfirmedTxs: rpc_test.go:365: Error Trace: rpc_test.go:365 Error: Not equal: expected: 1 actual : 0 Test: TestNumUnconfirmedTxs --- FAIL: TestNumUnconfirmedTxs (0.09s) ```
4 years ago
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
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
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
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
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
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
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
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
rpc: add support for batched requests/responses (#3534) Continues from #3280 in building support for batched requests/responses in the JSON RPC (as per issue #3213). * Add JSON RPC batching for client and server As per #3213, this adds support for [JSON RPC batch requests and responses](https://www.jsonrpc.org/specification#batch). * Add additional checks to ensure client responses are the same as results * Fix case where a notification is sent and no response is expected * Add test to check that JSON RPC notifications in a batch are left out in responses * Update CHANGELOG_PENDING.md * Update PR number now that PR has been created * Make errors start with lowercase letter * Refactor batch functionality to be standalone This refactors the batching functionality to rather act in a standalone way. In light of supporting concurrent goroutines making use of the same client, it would make sense to have batching functionality where one could create a batch of requests per goroutine and send that batch without interfering with a batch from another goroutine. * Add examples for simple and batch HTTP client usage * Check errors from writer and remove nolinter directives * Make error strings start with lowercase letter * Refactor examples to make them testable * Use safer deferred shutdown for example Tendermint test node * Recompose rpcClient interface from pre-existing interface components * Rename WaitGroup for brevity * Replace empty ID string with request ID * Remove extraneous test case * Convert first letter of errors.Wrap() messages to lowercase * Remove extraneous function parameter * Make variable declaration terse * Reorder WaitGroup.Done call to help prevent race conditions in the face of failure * Swap mutex to value representation and remove initialization * Restore empty JSONRPC string ID in response to prevent nil * Make JSONRPCBufferedRequest private * Revert PR hard link in CHANGELOG_PENDING * Add client ID for JSONRPCClient This adds code to automatically generate a randomized client ID for the JSONRPCClient, and adds a check of the IDs in the responses (if one was set in the requests). * Extract response ID validation into separate function * Remove extraneous comments * Reorder fields to indicate clearly which are protected by the mutex * Refactor for loop to remove indexing * Restructure and combine loop * Flatten conditional block for better readability * Make multi-variable declaration slightly more readable * Change for loop style * Compress error check statements * Make function description more generic to show that we support different protocols * Preallocate memory for request and result objects
5 years ago
  1. package client_test
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "math"
  9. "net/http"
  10. "strings"
  11. "sync"
  12. "testing"
  13. "time"
  14. "github.com/stretchr/testify/assert"
  15. "github.com/stretchr/testify/require"
  16. abci "github.com/tendermint/tendermint/abci/types"
  17. "github.com/tendermint/tendermint/config"
  18. "github.com/tendermint/tendermint/crypto/ed25519"
  19. "github.com/tendermint/tendermint/crypto/encoding"
  20. "github.com/tendermint/tendermint/internal/mempool"
  21. rpccore "github.com/tendermint/tendermint/internal/rpc/core"
  22. "github.com/tendermint/tendermint/libs/log"
  23. tmmath "github.com/tendermint/tendermint/libs/math"
  24. "github.com/tendermint/tendermint/libs/service"
  25. "github.com/tendermint/tendermint/privval"
  26. "github.com/tendermint/tendermint/rpc/client"
  27. rpchttp "github.com/tendermint/tendermint/rpc/client/http"
  28. rpclocal "github.com/tendermint/tendermint/rpc/client/local"
  29. "github.com/tendermint/tendermint/rpc/coretypes"
  30. rpcclient "github.com/tendermint/tendermint/rpc/jsonrpc/client"
  31. "github.com/tendermint/tendermint/types"
  32. )
  33. func getHTTPClient(t *testing.T, logger log.Logger, conf *config.Config) *rpchttp.HTTP {
  34. t.Helper()
  35. rpcAddr := conf.RPC.ListenAddress
  36. c, err := rpchttp.NewWithClient(rpcAddr, http.DefaultClient)
  37. require.NoError(t, err)
  38. ctx, cancel := context.WithCancel(context.Background())
  39. require.NoError(t, c.Start(ctx))
  40. c.Logger = logger
  41. t.Cleanup(func() {
  42. cancel()
  43. require.NoError(t, c.Stop())
  44. })
  45. return c
  46. }
  47. func getHTTPClientWithTimeout(t *testing.T, logger log.Logger, conf *config.Config, timeout time.Duration) *rpchttp.HTTP {
  48. t.Helper()
  49. rpcAddr := conf.RPC.ListenAddress
  50. tclient := &http.Client{Timeout: timeout}
  51. c, err := rpchttp.NewWithClient(rpcAddr, tclient)
  52. require.NoError(t, err)
  53. ctx, cancel := context.WithCancel(context.Background())
  54. require.NoError(t, c.Start(ctx))
  55. c.Logger = logger
  56. t.Cleanup(func() {
  57. cancel()
  58. require.NoError(t, c.Stop())
  59. })
  60. return c
  61. }
  62. // GetClients returns a slice of clients for table-driven tests
  63. func GetClients(t *testing.T, ns service.Service, conf *config.Config) []client.Client {
  64. t.Helper()
  65. node, ok := ns.(rpclocal.NodeService)
  66. require.True(t, ok)
  67. logger := log.NewTestingLogger(t)
  68. ncl, err := rpclocal.New(logger, node)
  69. require.NoError(t, err)
  70. return []client.Client{
  71. ncl,
  72. getHTTPClient(t, logger, conf),
  73. }
  74. }
  75. func TestClientOperations(t *testing.T) {
  76. ctx, cancel := context.WithCancel(context.Background())
  77. defer cancel()
  78. logger := log.NewTestingLogger(t)
  79. _, conf := NodeSuite(ctx, t, logger)
  80. t.Run("NilCustomHTTPClient", func(t *testing.T) {
  81. _, err := rpchttp.NewWithClient("http://example.com", nil)
  82. require.Error(t, err)
  83. _, err = rpcclient.NewWithHTTPClient("http://example.com", nil)
  84. require.Error(t, err)
  85. })
  86. t.Run("ParseInvalidAddress", func(t *testing.T) {
  87. // should remove trailing /
  88. invalidRemote := conf.RPC.ListenAddress + "/"
  89. _, err := rpchttp.New(invalidRemote)
  90. require.NoError(t, err)
  91. })
  92. t.Run("CustomHTTPClient", func(t *testing.T) {
  93. remote := conf.RPC.ListenAddress
  94. c, err := rpchttp.NewWithClient(remote, http.DefaultClient)
  95. require.NoError(t, err)
  96. status, err := c.Status(ctx)
  97. require.NoError(t, err)
  98. require.NotNil(t, status)
  99. })
  100. t.Run("CorsEnabled", func(t *testing.T) {
  101. origin := conf.RPC.CORSAllowedOrigins[0]
  102. remote := strings.ReplaceAll(conf.RPC.ListenAddress, "tcp", "http")
  103. req, err := http.NewRequestWithContext(ctx, "GET", remote, nil)
  104. require.NoError(t, err, "%+v", err)
  105. req.Header.Set("Origin", origin)
  106. resp, err := http.DefaultClient.Do(req)
  107. require.NoError(t, err, "%+v", err)
  108. defer resp.Body.Close()
  109. assert.Equal(t, resp.Header.Get("Access-Control-Allow-Origin"), origin)
  110. })
  111. t.Run("Batching", func(t *testing.T) {
  112. t.Run("JSONRPCCalls", func(t *testing.T) {
  113. logger := log.NewTestingLogger(t)
  114. c := getHTTPClient(t, logger, conf)
  115. testBatchedJSONRPCCalls(ctx, t, c)
  116. })
  117. t.Run("JSONRPCCallsCancellation", func(t *testing.T) {
  118. _, _, tx1 := MakeTxKV()
  119. _, _, tx2 := MakeTxKV()
  120. logger := log.NewTestingLogger(t)
  121. c := getHTTPClient(t, logger, conf)
  122. batch := c.NewBatch()
  123. _, err := batch.BroadcastTxCommit(ctx, tx1)
  124. require.NoError(t, err)
  125. _, err = batch.BroadcastTxCommit(ctx, tx2)
  126. require.NoError(t, err)
  127. // we should have 2 requests waiting
  128. require.Equal(t, 2, batch.Count())
  129. // we want to make sure we cleared 2 pending requests
  130. require.Equal(t, 2, batch.Clear())
  131. // now there should be no batched requests
  132. require.Equal(t, 0, batch.Count())
  133. })
  134. t.Run("SendingEmptyRequest", func(t *testing.T) {
  135. logger := log.NewTestingLogger(t)
  136. c := getHTTPClient(t, logger, conf)
  137. batch := c.NewBatch()
  138. _, err := batch.Send(ctx)
  139. require.Error(t, err, "sending an empty batch of JSON RPC requests should result in an error")
  140. })
  141. t.Run("ClearingEmptyRequest", func(t *testing.T) {
  142. logger := log.NewTestingLogger(t)
  143. c := getHTTPClient(t, logger, conf)
  144. batch := c.NewBatch()
  145. require.Zero(t, batch.Clear(), "clearing an empty batch of JSON RPC requests should result in a 0 result")
  146. })
  147. t.Run("ConcurrentJSONRPC", func(t *testing.T) {
  148. logger := log.NewTestingLogger(t)
  149. var wg sync.WaitGroup
  150. c := getHTTPClient(t, logger, conf)
  151. for i := 0; i < 50; i++ {
  152. wg.Add(1)
  153. go func() {
  154. defer wg.Done()
  155. testBatchedJSONRPCCalls(ctx, t, c)
  156. }()
  157. }
  158. wg.Wait()
  159. })
  160. })
  161. }
  162. // Make sure info is correct (we connect properly)
  163. func TestClientMethodCalls(t *testing.T) {
  164. ctx, cancel := context.WithCancel(context.Background())
  165. defer cancel()
  166. logger := log.NewTestingLogger(t)
  167. n, conf := NodeSuite(ctx, t, logger)
  168. // for broadcast tx tests
  169. pool := getMempool(t, n)
  170. // for evidence tests
  171. pv, err := privval.LoadOrGenFilePV(conf.PrivValidator.KeyFile(), conf.PrivValidator.StateFile())
  172. require.NoError(t, err)
  173. for i, c := range GetClients(t, n, conf) {
  174. t.Run(fmt.Sprintf("%T", c), func(t *testing.T) {
  175. t.Run("Status", func(t *testing.T) {
  176. status, err := c.Status(ctx)
  177. require.NoError(t, err, "%d: %+v", i, err)
  178. assert.Equal(t, conf.Moniker, status.NodeInfo.Moniker)
  179. })
  180. t.Run("Info", func(t *testing.T) {
  181. info, err := c.ABCIInfo(ctx)
  182. require.NoError(t, err)
  183. status, err := c.Status(ctx)
  184. require.NoError(t, err)
  185. assert.GreaterOrEqual(t, status.SyncInfo.LatestBlockHeight, info.Response.LastBlockHeight)
  186. assert.True(t, strings.Contains(info.Response.Data, "size"))
  187. })
  188. t.Run("NetInfo", func(t *testing.T) {
  189. nc, ok := c.(client.NetworkClient)
  190. require.True(t, ok, "%d", i)
  191. netinfo, err := nc.NetInfo(ctx)
  192. require.NoError(t, err, "%d: %+v", i, err)
  193. assert.True(t, netinfo.Listening)
  194. assert.Equal(t, 0, len(netinfo.Peers))
  195. })
  196. t.Run("DumpConsensusState", func(t *testing.T) {
  197. // FIXME: fix server so it doesn't panic on invalid input
  198. nc, ok := c.(client.NetworkClient)
  199. require.True(t, ok, "%d", i)
  200. cons, err := nc.DumpConsensusState(ctx)
  201. require.NoError(t, err, "%d: %+v", i, err)
  202. assert.NotEmpty(t, cons.RoundState)
  203. assert.Empty(t, cons.Peers)
  204. })
  205. t.Run("ConsensusState", func(t *testing.T) {
  206. // FIXME: fix server so it doesn't panic on invalid input
  207. nc, ok := c.(client.NetworkClient)
  208. require.True(t, ok, "%d", i)
  209. cons, err := nc.ConsensusState(ctx)
  210. require.NoError(t, err, "%d: %+v", i, err)
  211. assert.NotEmpty(t, cons.RoundState)
  212. })
  213. t.Run("Health", func(t *testing.T) {
  214. nc, ok := c.(client.NetworkClient)
  215. require.True(t, ok, "%d", i)
  216. _, err := nc.Health(ctx)
  217. require.NoError(t, err, "%d: %+v", i, err)
  218. })
  219. t.Run("GenesisAndValidators", func(t *testing.T) {
  220. // make sure this is the right genesis file
  221. gen, err := c.Genesis(ctx)
  222. require.NoError(t, err, "%d: %+v", i, err)
  223. // get the genesis validator
  224. require.Equal(t, 1, len(gen.Genesis.Validators))
  225. gval := gen.Genesis.Validators[0]
  226. // get the current validators
  227. h := int64(1)
  228. vals, err := c.Validators(ctx, &h, nil, nil)
  229. require.NoError(t, err, "%d: %+v", i, err)
  230. require.Equal(t, 1, len(vals.Validators))
  231. require.Equal(t, 1, vals.Count)
  232. require.Equal(t, 1, vals.Total)
  233. val := vals.Validators[0]
  234. // make sure the current set is also the genesis set
  235. assert.Equal(t, gval.Power, val.VotingPower)
  236. assert.Equal(t, gval.PubKey, val.PubKey)
  237. })
  238. t.Run("GenesisChunked", func(t *testing.T) {
  239. first, err := c.GenesisChunked(ctx, 0)
  240. require.NoError(t, err)
  241. decoded := make([]string, 0, first.TotalChunks)
  242. for i := 0; i < first.TotalChunks; i++ {
  243. chunk, err := c.GenesisChunked(ctx, uint(i))
  244. require.NoError(t, err)
  245. data, err := base64.StdEncoding.DecodeString(chunk.Data)
  246. require.NoError(t, err)
  247. decoded = append(decoded, string(data))
  248. }
  249. doc := []byte(strings.Join(decoded, ""))
  250. var out types.GenesisDoc
  251. require.NoError(t, json.Unmarshal(doc, &out),
  252. "first: %+v, doc: %s", first, string(doc))
  253. })
  254. t.Run("ABCIQuery", func(t *testing.T) {
  255. // write something
  256. k, v, tx := MakeTxKV()
  257. status, err := c.Status(ctx)
  258. require.NoError(t, err)
  259. _, err = c.BroadcastTxSync(ctx, tx)
  260. require.NoError(t, err, "%d: %+v", i, err)
  261. apph := status.SyncInfo.LatestBlockHeight + 2 // this is where the tx will be applied to the state
  262. // wait before querying
  263. err = client.WaitForHeight(ctx, c, apph, nil)
  264. require.NoError(t, err)
  265. res, err := c.ABCIQuery(ctx, "/key", k)
  266. qres := res.Response
  267. if assert.NoError(t, err) && assert.True(t, qres.IsOK()) {
  268. assert.EqualValues(t, v, qres.Value)
  269. }
  270. })
  271. t.Run("AppCalls", func(t *testing.T) {
  272. // get an offset of height to avoid racing and guessing
  273. s, err := c.Status(ctx)
  274. require.NoError(t, err)
  275. // sh is start height or status height
  276. sh := s.SyncInfo.LatestBlockHeight
  277. // look for the future
  278. h := sh + 20
  279. _, err = c.Block(ctx, &h)
  280. require.Error(t, err) // no block yet
  281. // write something
  282. k, v, tx := MakeTxKV()
  283. bres, err := c.BroadcastTxCommit(ctx, tx)
  284. require.NoError(t, err)
  285. require.True(t, bres.TxResult.IsOK())
  286. txh := bres.Height
  287. apph := txh + 1 // this is where the tx will be applied to the state
  288. // wait before querying
  289. err = client.WaitForHeight(ctx, c, apph, nil)
  290. require.NoError(t, err)
  291. _qres, err := c.ABCIQueryWithOptions(ctx, "/key", k, client.ABCIQueryOptions{Prove: false})
  292. require.NoError(t, err)
  293. qres := _qres.Response
  294. if assert.True(t, qres.IsOK()) {
  295. assert.Equal(t, k, qres.Key)
  296. assert.EqualValues(t, v, qres.Value)
  297. }
  298. // make sure we can lookup the tx with proof
  299. ptx, err := c.Tx(ctx, bres.Hash, true)
  300. require.NoError(t, err)
  301. assert.EqualValues(t, txh, ptx.Height)
  302. assert.EqualValues(t, tx, ptx.Tx)
  303. // and we can even check the block is added
  304. block, err := c.Block(ctx, &apph)
  305. require.NoError(t, err)
  306. appHash := block.Block.Header.AppHash
  307. assert.True(t, len(appHash) > 0)
  308. assert.EqualValues(t, apph, block.Block.Header.Height)
  309. blockByHash, err := c.BlockByHash(ctx, block.BlockID.Hash)
  310. require.NoError(t, err)
  311. require.Equal(t, block, blockByHash)
  312. // check that the header matches the block hash
  313. header, err := c.Header(ctx, &apph)
  314. require.NoError(t, err)
  315. require.Equal(t, block.Block.Header, *header.Header)
  316. headerByHash, err := c.HeaderByHash(ctx, block.BlockID.Hash)
  317. require.NoError(t, err)
  318. require.Equal(t, header, headerByHash)
  319. // now check the results
  320. blockResults, err := c.BlockResults(ctx, &txh)
  321. require.NoError(t, err, "%d: %+v", i, err)
  322. assert.Equal(t, txh, blockResults.Height)
  323. if assert.Equal(t, 1, len(blockResults.TxsResults)) {
  324. // check success code
  325. assert.EqualValues(t, 0, blockResults.TxsResults[0].Code)
  326. }
  327. // check blockchain info, now that we know there is info
  328. info, err := c.BlockchainInfo(ctx, apph, apph)
  329. require.NoError(t, err)
  330. assert.True(t, info.LastHeight >= apph)
  331. if assert.Equal(t, 1, len(info.BlockMetas)) {
  332. lastMeta := info.BlockMetas[0]
  333. assert.EqualValues(t, apph, lastMeta.Header.Height)
  334. blockData := block.Block
  335. assert.Equal(t, blockData.Header.AppHash, lastMeta.Header.AppHash)
  336. assert.Equal(t, block.BlockID, lastMeta.BlockID)
  337. }
  338. // and get the corresponding commit with the same apphash
  339. commit, err := c.Commit(ctx, &apph)
  340. require.NoError(t, err)
  341. cappHash := commit.Header.AppHash
  342. assert.Equal(t, appHash, cappHash)
  343. assert.NotNil(t, commit.Commit)
  344. // compare the commits (note Commit(2) has commit from Block(3))
  345. h = apph - 1
  346. commit2, err := c.Commit(ctx, &h)
  347. require.NoError(t, err)
  348. assert.Equal(t, block.Block.LastCommitHash, commit2.Commit.Hash())
  349. // and we got a proof that works!
  350. _pres, err := c.ABCIQueryWithOptions(ctx, "/key", k, client.ABCIQueryOptions{Prove: true})
  351. require.NoError(t, err)
  352. pres := _pres.Response
  353. assert.True(t, pres.IsOK())
  354. // XXX Test proof
  355. })
  356. t.Run("BlockchainInfo", func(t *testing.T) {
  357. ctx, cancel := context.WithCancel(context.Background())
  358. defer cancel()
  359. err := client.WaitForHeight(ctx, c, 10, nil)
  360. require.NoError(t, err)
  361. res, err := c.BlockchainInfo(ctx, 0, 0)
  362. require.NoError(t, err, "%d: %+v", i, err)
  363. assert.True(t, res.LastHeight > 0)
  364. assert.True(t, len(res.BlockMetas) > 0)
  365. res, err = c.BlockchainInfo(ctx, 1, 1)
  366. require.NoError(t, err, "%d: %+v", i, err)
  367. assert.True(t, res.LastHeight > 0)
  368. assert.True(t, len(res.BlockMetas) == 1)
  369. res, err = c.BlockchainInfo(ctx, 1, 10000)
  370. require.NoError(t, err, "%d: %+v", i, err)
  371. assert.True(t, res.LastHeight > 0)
  372. assert.True(t, len(res.BlockMetas) < 100)
  373. for _, m := range res.BlockMetas {
  374. assert.NotNil(t, m)
  375. }
  376. res, err = c.BlockchainInfo(ctx, 10000, 1)
  377. require.Error(t, err)
  378. assert.Nil(t, res)
  379. assert.Contains(t, err.Error(), "can't be greater than max")
  380. })
  381. t.Run("BroadcastTxCommit", func(t *testing.T) {
  382. _, _, tx := MakeTxKV()
  383. bres, err := c.BroadcastTxCommit(ctx, tx)
  384. require.NoError(t, err, "%d: %+v", i, err)
  385. require.True(t, bres.CheckTx.IsOK())
  386. require.True(t, bres.TxResult.IsOK())
  387. require.Equal(t, 0, pool.Size())
  388. })
  389. t.Run("BroadcastTxSync", func(t *testing.T) {
  390. _, _, tx := MakeTxKV()
  391. initMempoolSize := pool.Size()
  392. bres, err := c.BroadcastTxSync(ctx, tx)
  393. require.NoError(t, err, "%d: %+v", i, err)
  394. require.Equal(t, bres.Code, abci.CodeTypeOK) // FIXME
  395. require.Equal(t, initMempoolSize+1, pool.Size())
  396. txs := pool.ReapMaxTxs(len(tx))
  397. require.EqualValues(t, tx, txs[0])
  398. pool.Flush()
  399. })
  400. t.Run("CheckTx", func(t *testing.T) {
  401. _, _, tx := MakeTxKV()
  402. res, err := c.CheckTx(ctx, tx)
  403. require.NoError(t, err)
  404. assert.Equal(t, abci.CodeTypeOK, res.Code)
  405. assert.Equal(t, 0, pool.Size(), "mempool must be empty")
  406. })
  407. t.Run("Events", func(t *testing.T) {
  408. t.Run("Header", func(t *testing.T) {
  409. ctx, cancel := context.WithTimeout(ctx, waitForEventTimeout)
  410. defer cancel()
  411. query := types.QueryForEvent(types.EventNewBlockHeaderValue).String()
  412. evt, err := client.WaitForOneEvent(ctx, c, query)
  413. require.NoError(t, err, "%d: %+v", i, err)
  414. _, ok := evt.(types.EventDataNewBlockHeader)
  415. require.True(t, ok, "%d: %#v", i, evt)
  416. // TODO: more checks...
  417. })
  418. t.Run("Block", func(t *testing.T) {
  419. const subscriber = "TestBlockEvents"
  420. eventCh, err := c.Subscribe(ctx, subscriber, types.QueryForEvent(types.EventNewBlockValue).String())
  421. require.NoError(t, err)
  422. t.Cleanup(func() {
  423. if err := c.UnsubscribeAll(ctx, subscriber); err != nil {
  424. t.Error(err)
  425. }
  426. })
  427. var firstBlockHeight int64
  428. for i := int64(0); i < 3; i++ {
  429. event := <-eventCh
  430. blockEvent, ok := event.Data.(types.EventDataNewBlock)
  431. require.True(t, ok)
  432. block := blockEvent.Block
  433. if firstBlockHeight == 0 {
  434. firstBlockHeight = block.Header.Height
  435. }
  436. require.Equal(t, firstBlockHeight+i, block.Header.Height)
  437. }
  438. })
  439. t.Run("BroadcastTxAsync", func(t *testing.T) {
  440. testTxEventsSent(ctx, t, "async", c)
  441. })
  442. t.Run("BroadcastTxSync", func(t *testing.T) {
  443. testTxEventsSent(ctx, t, "sync", c)
  444. })
  445. })
  446. t.Run("Evidence", func(t *testing.T) {
  447. t.Run("BroadcastDuplicateVote", func(t *testing.T) {
  448. ctx, cancel := context.WithCancel(context.Background())
  449. defer cancel()
  450. chainID := conf.ChainID()
  451. // make sure that the node has produced enough blocks
  452. waitForBlock(ctx, t, c, 2)
  453. evidenceHeight := int64(1)
  454. block, _ := c.Block(ctx, &evidenceHeight)
  455. ts := block.Block.Time
  456. correct, fakes := makeEvidences(t, pv, chainID, ts)
  457. result, err := c.BroadcastEvidence(ctx, correct)
  458. require.NoError(t, err, "BroadcastEvidence(%s) failed", correct)
  459. assert.Equal(t, correct.Hash(), result.Hash, "expected result hash to match evidence hash")
  460. status, err := c.Status(ctx)
  461. require.NoError(t, err)
  462. err = client.WaitForHeight(ctx, c, status.SyncInfo.LatestBlockHeight+2, nil)
  463. require.NoError(t, err)
  464. ed25519pub := pv.Key.PubKey.(ed25519.PubKey)
  465. rawpub := ed25519pub.Bytes()
  466. result2, err := c.ABCIQuery(ctx, "/val", rawpub)
  467. require.NoError(t, err)
  468. qres := result2.Response
  469. require.True(t, qres.IsOK())
  470. var v abci.ValidatorUpdate
  471. err = abci.ReadMessage(bytes.NewReader(qres.Value), &v)
  472. require.NoError(t, err, "Error reading query result, value %v", qres.Value)
  473. pk, err := encoding.PubKeyFromProto(v.PubKey)
  474. require.NoError(t, err)
  475. require.EqualValues(t, rawpub, pk, "Stored PubKey not equal with expected, value %v", string(qres.Value))
  476. require.Equal(t, int64(9), v.Power, "Stored Power not equal with expected, value %v", string(qres.Value))
  477. for _, fake := range fakes {
  478. _, err := c.BroadcastEvidence(ctx, fake)
  479. require.Error(t, err, "BroadcastEvidence(%s) succeeded, but the evidence was fake", fake)
  480. }
  481. })
  482. t.Run("BroadcastEmpty", func(t *testing.T) {
  483. _, err := c.BroadcastEvidence(ctx, nil)
  484. require.Error(t, err)
  485. })
  486. })
  487. })
  488. }
  489. }
  490. func getMempool(t *testing.T, srv service.Service) mempool.Mempool {
  491. t.Helper()
  492. n, ok := srv.(interface {
  493. RPCEnvironment() *rpccore.Environment
  494. })
  495. require.True(t, ok)
  496. return n.RPCEnvironment().Mempool
  497. }
  498. // these cases are roughly the same as the TestClientMethodCalls, but
  499. // they have to loop over their clients in the individual test cases,
  500. // so making a separate suite makes more sense, though isn't strictly
  501. // speaking desirable.
  502. func TestClientMethodCallsAdvanced(t *testing.T) {
  503. ctx, cancel := context.WithCancel(context.Background())
  504. defer cancel()
  505. logger := log.NewTestingLogger(t)
  506. n, conf := NodeSuite(ctx, t, logger)
  507. pool := getMempool(t, n)
  508. t.Run("UnconfirmedTxs", func(t *testing.T) {
  509. // populate mempool with 5 tx
  510. txs := make([]types.Tx, 5)
  511. ch := make(chan error, 5)
  512. for i := 0; i < 5; i++ {
  513. _, _, tx := MakeTxKV()
  514. txs[i] = tx
  515. err := pool.CheckTx(ctx, tx, func(_ *abci.ResponseCheckTx) { ch <- nil }, mempool.TxInfo{})
  516. require.NoError(t, err)
  517. }
  518. // wait for tx to arrive in mempoool.
  519. for i := 0; i < 5; i++ {
  520. select {
  521. case <-ch:
  522. case <-time.After(5 * time.Second):
  523. t.Error("Timed out waiting for CheckTx callback")
  524. }
  525. }
  526. close(ch)
  527. for _, c := range GetClients(t, n, conf) {
  528. for i := 1; i <= 2; i++ {
  529. mc := c.(client.MempoolClient)
  530. page, perPage := i, 3
  531. res, err := mc.UnconfirmedTxs(ctx, &page, &perPage)
  532. require.NoError(t, err)
  533. if i == 2 {
  534. perPage = 2
  535. }
  536. assert.Equal(t, perPage, res.Count)
  537. assert.Equal(t, 5, res.Total)
  538. assert.Equal(t, pool.SizeBytes(), res.TotalBytes)
  539. for _, tx := range res.Txs {
  540. assert.Contains(t, txs, tx)
  541. }
  542. }
  543. }
  544. pool.Flush()
  545. })
  546. t.Run("NumUnconfirmedTxs", func(t *testing.T) {
  547. ch := make(chan struct{})
  548. pool := getMempool(t, n)
  549. _, _, tx := MakeTxKV()
  550. err := pool.CheckTx(ctx, tx, func(_ *abci.ResponseCheckTx) { close(ch) }, mempool.TxInfo{})
  551. require.NoError(t, err)
  552. // wait for tx to arrive in mempoool.
  553. select {
  554. case <-ch:
  555. case <-time.After(5 * time.Second):
  556. t.Error("Timed out waiting for CheckTx callback")
  557. }
  558. mempoolSize := pool.Size()
  559. for i, c := range GetClients(t, n, conf) {
  560. mc, ok := c.(client.MempoolClient)
  561. require.True(t, ok, "%d", i)
  562. res, err := mc.NumUnconfirmedTxs(ctx)
  563. require.NoError(t, err, "%d: %+v", i, err)
  564. assert.Equal(t, mempoolSize, res.Count)
  565. assert.Equal(t, mempoolSize, res.Total)
  566. assert.Equal(t, pool.SizeBytes(), res.TotalBytes)
  567. }
  568. pool.Flush()
  569. })
  570. t.Run("Tx", func(t *testing.T) {
  571. logger := log.NewTestingLogger(t)
  572. c := getHTTPClient(t, logger, conf)
  573. // first we broadcast a tx
  574. _, _, tx := MakeTxKV()
  575. bres, err := c.BroadcastTxCommit(ctx, tx)
  576. require.NoError(t, err, "%+v", err)
  577. txHeight := bres.Height
  578. txHash := bres.Hash
  579. anotherTxHash := types.Tx("a different tx").Hash()
  580. cases := []struct {
  581. valid bool
  582. prove bool
  583. hash []byte
  584. }{
  585. // only valid if correct hash provided
  586. {true, false, txHash},
  587. {true, true, txHash},
  588. {false, false, anotherTxHash},
  589. {false, true, anotherTxHash},
  590. {false, false, nil},
  591. {false, true, nil},
  592. }
  593. for _, c := range GetClients(t, n, conf) {
  594. t.Run(fmt.Sprintf("%T", c), func(t *testing.T) {
  595. for j, tc := range cases {
  596. t.Run(fmt.Sprintf("Case%d", j), func(t *testing.T) {
  597. // now we query for the tx.
  598. // since there's only one tx, we know index=0.
  599. ptx, err := c.Tx(ctx, tc.hash, tc.prove)
  600. if !tc.valid {
  601. require.Error(t, err)
  602. } else {
  603. require.NoError(t, err, "%+v", err)
  604. assert.EqualValues(t, txHeight, ptx.Height)
  605. assert.EqualValues(t, tx, ptx.Tx)
  606. assert.Zero(t, ptx.Index)
  607. assert.True(t, ptx.TxResult.IsOK())
  608. assert.EqualValues(t, txHash, ptx.Hash)
  609. // time to verify the proof
  610. proof := ptx.Proof
  611. if tc.prove && assert.EqualValues(t, tx, proof.Data) {
  612. assert.NoError(t, proof.Proof.Verify(proof.RootHash, txHash))
  613. }
  614. }
  615. })
  616. }
  617. })
  618. }
  619. })
  620. t.Run("TxSearchWithTimeout", func(t *testing.T) {
  621. logger := log.NewTestingLogger(t)
  622. timeoutClient := getHTTPClientWithTimeout(t, logger, conf, 10*time.Second)
  623. _, _, tx := MakeTxKV()
  624. _, err := timeoutClient.BroadcastTxCommit(ctx, tx)
  625. require.NoError(t, err)
  626. // query using a compositeKey (see kvstore application)
  627. result, err := timeoutClient.TxSearch(ctx, "app.creator='Cosmoshi Netowoko'", false, nil, nil, "asc")
  628. require.NoError(t, err)
  629. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  630. })
  631. t.Run("TxSearch", func(t *testing.T) {
  632. t.Skip("Test Asserts Non-Deterministic Results")
  633. logger := log.NewTestingLogger(t)
  634. c := getHTTPClient(t, logger, conf)
  635. // first we broadcast a few txs
  636. for i := 0; i < 10; i++ {
  637. _, _, tx := MakeTxKV()
  638. _, err := c.BroadcastTxSync(ctx, tx)
  639. require.NoError(t, err)
  640. }
  641. // since we're not using an isolated test server, we'll have lingering transactions
  642. // from other tests as well
  643. result, err := c.TxSearch(ctx, "tx.height >= 0", true, nil, nil, "asc")
  644. require.NoError(t, err)
  645. txCount := len(result.Txs)
  646. // pick out the last tx to have something to search for in tests
  647. find := result.Txs[len(result.Txs)-1]
  648. anotherTxHash := types.Tx("a different tx").Hash()
  649. for _, c := range GetClients(t, n, conf) {
  650. t.Run(fmt.Sprintf("%T", c), func(t *testing.T) {
  651. // now we query for the tx.
  652. result, err := c.TxSearch(ctx, fmt.Sprintf("tx.hash='%v'", find.Hash), true, nil, nil, "asc")
  653. require.NoError(t, err)
  654. require.Len(t, result.Txs, 1)
  655. require.Equal(t, find.Hash, result.Txs[0].Hash)
  656. ptx := result.Txs[0]
  657. assert.EqualValues(t, find.Height, ptx.Height)
  658. assert.EqualValues(t, find.Tx, ptx.Tx)
  659. assert.Zero(t, ptx.Index)
  660. assert.True(t, ptx.TxResult.IsOK())
  661. assert.EqualValues(t, find.Hash, ptx.Hash)
  662. // time to verify the proof
  663. if assert.EqualValues(t, find.Tx, ptx.Proof.Data) {
  664. assert.NoError(t, ptx.Proof.Proof.Verify(ptx.Proof.RootHash, find.Hash))
  665. }
  666. // query by height
  667. result, err = c.TxSearch(ctx, fmt.Sprintf("tx.height=%d", find.Height), true, nil, nil, "asc")
  668. require.NoError(t, err)
  669. require.Len(t, result.Txs, 1)
  670. // query for non existing tx
  671. result, err = c.TxSearch(ctx, fmt.Sprintf("tx.hash='%X'", anotherTxHash), false, nil, nil, "asc")
  672. require.NoError(t, err)
  673. require.Len(t, result.Txs, 0)
  674. // query using a compositeKey (see kvstore application)
  675. result, err = c.TxSearch(ctx, "app.creator='Cosmoshi Netowoko'", false, nil, nil, "asc")
  676. require.NoError(t, err)
  677. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  678. // query using an index key
  679. result, err = c.TxSearch(ctx, "app.index_key='index is working'", false, nil, nil, "asc")
  680. require.NoError(t, err)
  681. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  682. // query using an noindex key
  683. result, err = c.TxSearch(ctx, "app.noindex_key='index is working'", false, nil, nil, "asc")
  684. require.NoError(t, err)
  685. require.Equal(t, len(result.Txs), 0, "expected a lot of transactions")
  686. // query using a compositeKey (see kvstore application) and height
  687. result, err = c.TxSearch(ctx,
  688. "app.creator='Cosmoshi Netowoko' AND tx.height<10000", true, nil, nil, "asc")
  689. require.NoError(t, err)
  690. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  691. // query a non existing tx with page 1 and txsPerPage 1
  692. perPage := 1
  693. result, err = c.TxSearch(ctx, "app.creator='Cosmoshi Neetowoko'", true, nil, &perPage, "asc")
  694. require.NoError(t, err)
  695. require.Len(t, result.Txs, 0)
  696. // check sorting
  697. result, err = c.TxSearch(ctx, "tx.height >= 1", false, nil, nil, "asc")
  698. require.NoError(t, err)
  699. for k := 0; k < len(result.Txs)-1; k++ {
  700. require.LessOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height)
  701. require.LessOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index)
  702. }
  703. result, err = c.TxSearch(ctx, "tx.height >= 1", false, nil, nil, "desc")
  704. require.NoError(t, err)
  705. for k := 0; k < len(result.Txs)-1; k++ {
  706. require.GreaterOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height)
  707. require.GreaterOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index)
  708. }
  709. // check pagination
  710. perPage = 3
  711. var (
  712. seen = map[int64]bool{}
  713. maxHeight int64
  714. pages = int(math.Ceil(float64(txCount) / float64(perPage)))
  715. )
  716. for page := 1; page <= pages; page++ {
  717. page := page
  718. result, err := c.TxSearch(ctx, "tx.height >= 1", false, &page, &perPage, "asc")
  719. require.NoError(t, err)
  720. if page < pages {
  721. require.Len(t, result.Txs, perPage)
  722. } else {
  723. require.LessOrEqual(t, len(result.Txs), perPage)
  724. }
  725. require.Equal(t, txCount, result.TotalCount)
  726. for _, tx := range result.Txs {
  727. require.False(t, seen[tx.Height],
  728. "Found duplicate height %v in page %v", tx.Height, page)
  729. require.Greater(t, tx.Height, maxHeight,
  730. "Found decreasing height %v (max seen %v) in page %v", tx.Height, maxHeight, page)
  731. seen[tx.Height] = true
  732. maxHeight = tx.Height
  733. }
  734. }
  735. require.Len(t, seen, txCount)
  736. })
  737. }
  738. })
  739. }
  740. func testBatchedJSONRPCCalls(ctx context.Context, t *testing.T, c *rpchttp.HTTP) {
  741. k1, v1, tx1 := MakeTxKV()
  742. k2, v2, tx2 := MakeTxKV()
  743. batch := c.NewBatch()
  744. r1, err := batch.BroadcastTxCommit(ctx, tx1)
  745. require.NoError(t, err)
  746. r2, err := batch.BroadcastTxCommit(ctx, tx2)
  747. require.NoError(t, err)
  748. require.Equal(t, 2, batch.Count())
  749. bresults, err := batch.Send(ctx)
  750. require.NoError(t, err)
  751. require.Len(t, bresults, 2)
  752. require.Equal(t, 0, batch.Count())
  753. bresult1, ok := bresults[0].(*coretypes.ResultBroadcastTxCommit)
  754. require.True(t, ok)
  755. require.Equal(t, *bresult1, *r1)
  756. bresult2, ok := bresults[1].(*coretypes.ResultBroadcastTxCommit)
  757. require.True(t, ok)
  758. require.Equal(t, *bresult2, *r2)
  759. apph := tmmath.MaxInt64(bresult1.Height, bresult2.Height) + 1
  760. err = client.WaitForHeight(ctx, c, apph, nil)
  761. require.NoError(t, err)
  762. q1, err := batch.ABCIQuery(ctx, "/key", k1)
  763. require.NoError(t, err)
  764. q2, err := batch.ABCIQuery(ctx, "/key", k2)
  765. require.NoError(t, err)
  766. require.Equal(t, 2, batch.Count())
  767. qresults, err := batch.Send(ctx)
  768. require.NoError(t, err)
  769. require.Len(t, qresults, 2)
  770. require.Equal(t, 0, batch.Count())
  771. qresult1, ok := qresults[0].(*coretypes.ResultABCIQuery)
  772. require.True(t, ok)
  773. require.Equal(t, *qresult1, *q1)
  774. qresult2, ok := qresults[1].(*coretypes.ResultABCIQuery)
  775. require.True(t, ok)
  776. require.Equal(t, *qresult2, *q2)
  777. require.Equal(t, qresult1.Response.Key, k1)
  778. require.Equal(t, qresult2.Response.Key, k2)
  779. require.Equal(t, qresult1.Response.Value, v1)
  780. require.Equal(t, qresult2.Response.Value, v2)
  781. }