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.

909 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
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(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(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.DeliverTx.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.DeliverTx.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. evt, err := client.WaitForOneEvent(c, types.EventNewBlockHeaderValue, waitForEventTimeout)
  410. require.NoError(t, err, "%d: %+v", i, err)
  411. _, ok := evt.(types.EventDataNewBlockHeader)
  412. require.True(t, ok, "%d: %#v", i, evt)
  413. // TODO: more checks...
  414. })
  415. t.Run("Block", func(t *testing.T) {
  416. const subscriber = "TestBlockEvents"
  417. eventCh, err := c.Subscribe(ctx, subscriber, types.QueryForEvent(types.EventNewBlockValue).String())
  418. require.NoError(t, err)
  419. t.Cleanup(func() {
  420. if err := c.UnsubscribeAll(ctx, subscriber); err != nil {
  421. t.Error(err)
  422. }
  423. })
  424. var firstBlockHeight int64
  425. for i := int64(0); i < 3; i++ {
  426. event := <-eventCh
  427. blockEvent, ok := event.Data.(types.EventDataNewBlock)
  428. require.True(t, ok)
  429. block := blockEvent.Block
  430. if firstBlockHeight == 0 {
  431. firstBlockHeight = block.Header.Height
  432. }
  433. require.Equal(t, firstBlockHeight+i, block.Header.Height)
  434. }
  435. })
  436. t.Run("BroadcastTxAsync", func(t *testing.T) {
  437. testTxEventsSent(ctx, t, "async", c)
  438. })
  439. t.Run("BroadcastTxSync", func(t *testing.T) {
  440. testTxEventsSent(ctx, t, "sync", c)
  441. })
  442. })
  443. t.Run("Evidence", func(t *testing.T) {
  444. t.Run("BroadcastDuplicateVote", func(t *testing.T) {
  445. ctx, cancel := context.WithCancel(context.Background())
  446. defer cancel()
  447. chainID := conf.ChainID()
  448. // make sure that the node has produced enough blocks
  449. waitForBlock(ctx, t, c, 2)
  450. evidenceHeight := int64(1)
  451. block, _ := c.Block(ctx, &evidenceHeight)
  452. ts := block.Block.Time
  453. correct, fakes := makeEvidences(t, pv, chainID, ts)
  454. result, err := c.BroadcastEvidence(ctx, correct)
  455. require.NoError(t, err, "BroadcastEvidence(%s) failed", correct)
  456. assert.Equal(t, correct.Hash(), result.Hash, "expected result hash to match evidence hash")
  457. status, err := c.Status(ctx)
  458. require.NoError(t, err)
  459. err = client.WaitForHeight(ctx, c, status.SyncInfo.LatestBlockHeight+2, nil)
  460. require.NoError(t, err)
  461. ed25519pub := pv.Key.PubKey.(ed25519.PubKey)
  462. rawpub := ed25519pub.Bytes()
  463. result2, err := c.ABCIQuery(ctx, "/val", rawpub)
  464. require.NoError(t, err)
  465. qres := result2.Response
  466. require.True(t, qres.IsOK())
  467. var v abci.ValidatorUpdate
  468. err = abci.ReadMessage(bytes.NewReader(qres.Value), &v)
  469. require.NoError(t, err, "Error reading query result, value %v", qres.Value)
  470. pk, err := encoding.PubKeyFromProto(v.PubKey)
  471. require.NoError(t, err)
  472. require.EqualValues(t, rawpub, pk, "Stored PubKey not equal with expected, value %v", string(qres.Value))
  473. require.Equal(t, int64(9), v.Power, "Stored Power not equal with expected, value %v", string(qres.Value))
  474. for _, fake := range fakes {
  475. _, err := c.BroadcastEvidence(ctx, fake)
  476. require.Error(t, err, "BroadcastEvidence(%s) succeeded, but the evidence was fake", fake)
  477. }
  478. })
  479. t.Run("BroadcastEmpty", func(t *testing.T) {
  480. _, err := c.BroadcastEvidence(ctx, nil)
  481. require.Error(t, err)
  482. })
  483. })
  484. })
  485. }
  486. }
  487. func getMempool(t *testing.T, srv service.Service) mempool.Mempool {
  488. t.Helper()
  489. n, ok := srv.(interface {
  490. RPCEnvironment() *rpccore.Environment
  491. })
  492. require.True(t, ok)
  493. return n.RPCEnvironment().Mempool
  494. }
  495. // these cases are roughly the same as the TestClientMethodCalls, but
  496. // they have to loop over their clients in the individual test cases,
  497. // so making a separate suite makes more sense, though isn't strictly
  498. // speaking desirable.
  499. func TestClientMethodCallsAdvanced(t *testing.T) {
  500. ctx, cancel := context.WithCancel(context.Background())
  501. defer cancel()
  502. logger := log.NewTestingLogger(t)
  503. n, conf := NodeSuite(t, logger)
  504. pool := getMempool(t, n)
  505. t.Run("UnconfirmedTxs", func(t *testing.T) {
  506. // populate mempool with 5 tx
  507. txs := make([]types.Tx, 5)
  508. ch := make(chan error, 5)
  509. for i := 0; i < 5; i++ {
  510. _, _, tx := MakeTxKV()
  511. txs[i] = tx
  512. err := pool.CheckTx(ctx, tx, func(_ *abci.ResponseCheckTx) { ch <- nil }, mempool.TxInfo{})
  513. require.NoError(t, err)
  514. }
  515. // wait for tx to arrive in mempoool.
  516. for i := 0; i < 5; i++ {
  517. select {
  518. case <-ch:
  519. case <-time.After(5 * time.Second):
  520. t.Error("Timed out waiting for CheckTx callback")
  521. }
  522. }
  523. close(ch)
  524. for _, c := range GetClients(t, n, conf) {
  525. for i := 1; i <= 2; i++ {
  526. mc := c.(client.MempoolClient)
  527. page, perPage := i, 3
  528. res, err := mc.UnconfirmedTxs(ctx, &page, &perPage)
  529. require.NoError(t, err)
  530. if i == 2 {
  531. perPage = 2
  532. }
  533. assert.Equal(t, perPage, res.Count)
  534. assert.Equal(t, 5, res.Total)
  535. assert.Equal(t, pool.SizeBytes(), res.TotalBytes)
  536. for _, tx := range res.Txs {
  537. assert.Contains(t, txs, tx)
  538. }
  539. }
  540. }
  541. pool.Flush()
  542. })
  543. t.Run("NumUnconfirmedTxs", func(t *testing.T) {
  544. ch := make(chan struct{})
  545. pool := getMempool(t, n)
  546. _, _, tx := MakeTxKV()
  547. err := pool.CheckTx(ctx, tx, func(_ *abci.ResponseCheckTx) { close(ch) }, mempool.TxInfo{})
  548. require.NoError(t, err)
  549. // wait for tx to arrive in mempoool.
  550. select {
  551. case <-ch:
  552. case <-time.After(5 * time.Second):
  553. t.Error("Timed out waiting for CheckTx callback")
  554. }
  555. mempoolSize := pool.Size()
  556. for i, c := range GetClients(t, n, conf) {
  557. mc, ok := c.(client.MempoolClient)
  558. require.True(t, ok, "%d", i)
  559. res, err := mc.NumUnconfirmedTxs(ctx)
  560. require.NoError(t, err, "%d: %+v", i, err)
  561. assert.Equal(t, mempoolSize, res.Count)
  562. assert.Equal(t, mempoolSize, res.Total)
  563. assert.Equal(t, pool.SizeBytes(), res.TotalBytes)
  564. }
  565. pool.Flush()
  566. })
  567. t.Run("Tx", func(t *testing.T) {
  568. logger := log.NewTestingLogger(t)
  569. c := getHTTPClient(t, logger, conf)
  570. // first we broadcast a tx
  571. _, _, tx := MakeTxKV()
  572. bres, err := c.BroadcastTxCommit(ctx, tx)
  573. require.NoError(t, err, "%+v", err)
  574. txHeight := bres.Height
  575. txHash := bres.Hash
  576. anotherTxHash := types.Tx("a different tx").Hash()
  577. cases := []struct {
  578. valid bool
  579. prove bool
  580. hash []byte
  581. }{
  582. // only valid if correct hash provided
  583. {true, false, txHash},
  584. {true, true, txHash},
  585. {false, false, anotherTxHash},
  586. {false, true, anotherTxHash},
  587. {false, false, nil},
  588. {false, true, nil},
  589. }
  590. for _, c := range GetClients(t, n, conf) {
  591. t.Run(fmt.Sprintf("%T", c), func(t *testing.T) {
  592. for j, tc := range cases {
  593. t.Run(fmt.Sprintf("Case%d", j), func(t *testing.T) {
  594. // now we query for the tx.
  595. // since there's only one tx, we know index=0.
  596. ptx, err := c.Tx(ctx, tc.hash, tc.prove)
  597. if !tc.valid {
  598. require.Error(t, err)
  599. } else {
  600. require.NoError(t, err, "%+v", err)
  601. assert.EqualValues(t, txHeight, ptx.Height)
  602. assert.EqualValues(t, tx, ptx.Tx)
  603. assert.Zero(t, ptx.Index)
  604. assert.True(t, ptx.TxResult.IsOK())
  605. assert.EqualValues(t, txHash, ptx.Hash)
  606. // time to verify the proof
  607. proof := ptx.Proof
  608. if tc.prove && assert.EqualValues(t, tx, proof.Data) {
  609. assert.NoError(t, proof.Proof.Verify(proof.RootHash, txHash))
  610. }
  611. }
  612. })
  613. }
  614. })
  615. }
  616. })
  617. t.Run("TxSearchWithTimeout", func(t *testing.T) {
  618. logger := log.NewTestingLogger(t)
  619. timeoutClient := getHTTPClientWithTimeout(t, logger, conf, 10*time.Second)
  620. _, _, tx := MakeTxKV()
  621. _, err := timeoutClient.BroadcastTxCommit(ctx, tx)
  622. require.NoError(t, err)
  623. // query using a compositeKey (see kvstore application)
  624. result, err := timeoutClient.TxSearch(ctx, "app.creator='Cosmoshi Netowoko'", false, nil, nil, "asc")
  625. require.NoError(t, err)
  626. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  627. })
  628. t.Run("TxSearch", func(t *testing.T) {
  629. t.Skip("Test Asserts Non-Deterministic Results")
  630. logger := log.NewTestingLogger(t)
  631. c := getHTTPClient(t, logger, conf)
  632. // first we broadcast a few txs
  633. for i := 0; i < 10; i++ {
  634. _, _, tx := MakeTxKV()
  635. _, err := c.BroadcastTxSync(ctx, tx)
  636. require.NoError(t, err)
  637. }
  638. // since we're not using an isolated test server, we'll have lingering transactions
  639. // from other tests as well
  640. result, err := c.TxSearch(ctx, "tx.height >= 0", true, nil, nil, "asc")
  641. require.NoError(t, err)
  642. txCount := len(result.Txs)
  643. // pick out the last tx to have something to search for in tests
  644. find := result.Txs[len(result.Txs)-1]
  645. anotherTxHash := types.Tx("a different tx").Hash()
  646. for _, c := range GetClients(t, n, conf) {
  647. t.Run(fmt.Sprintf("%T", c), func(t *testing.T) {
  648. // now we query for the tx.
  649. result, err := c.TxSearch(ctx, fmt.Sprintf("tx.hash='%v'", find.Hash), true, nil, nil, "asc")
  650. require.NoError(t, err)
  651. require.Len(t, result.Txs, 1)
  652. require.Equal(t, find.Hash, result.Txs[0].Hash)
  653. ptx := result.Txs[0]
  654. assert.EqualValues(t, find.Height, ptx.Height)
  655. assert.EqualValues(t, find.Tx, ptx.Tx)
  656. assert.Zero(t, ptx.Index)
  657. assert.True(t, ptx.TxResult.IsOK())
  658. assert.EqualValues(t, find.Hash, ptx.Hash)
  659. // time to verify the proof
  660. if assert.EqualValues(t, find.Tx, ptx.Proof.Data) {
  661. assert.NoError(t, ptx.Proof.Proof.Verify(ptx.Proof.RootHash, find.Hash))
  662. }
  663. // query by height
  664. result, err = c.TxSearch(ctx, fmt.Sprintf("tx.height=%d", find.Height), true, nil, nil, "asc")
  665. require.NoError(t, err)
  666. require.Len(t, result.Txs, 1)
  667. // query for non existing tx
  668. result, err = c.TxSearch(ctx, fmt.Sprintf("tx.hash='%X'", anotherTxHash), false, nil, nil, "asc")
  669. require.NoError(t, err)
  670. require.Len(t, result.Txs, 0)
  671. // query using a compositeKey (see kvstore application)
  672. result, err = c.TxSearch(ctx, "app.creator='Cosmoshi Netowoko'", false, nil, nil, "asc")
  673. require.NoError(t, err)
  674. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  675. // query using an index key
  676. result, err = c.TxSearch(ctx, "app.index_key='index is working'", false, nil, nil, "asc")
  677. require.NoError(t, err)
  678. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  679. // query using an noindex key
  680. result, err = c.TxSearch(ctx, "app.noindex_key='index is working'", false, nil, nil, "asc")
  681. require.NoError(t, err)
  682. require.Equal(t, len(result.Txs), 0, "expected a lot of transactions")
  683. // query using a compositeKey (see kvstore application) and height
  684. result, err = c.TxSearch(ctx,
  685. "app.creator='Cosmoshi Netowoko' AND tx.height<10000", true, nil, nil, "asc")
  686. require.NoError(t, err)
  687. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  688. // query a non existing tx with page 1 and txsPerPage 1
  689. perPage := 1
  690. result, err = c.TxSearch(ctx, "app.creator='Cosmoshi Neetowoko'", true, nil, &perPage, "asc")
  691. require.NoError(t, err)
  692. require.Len(t, result.Txs, 0)
  693. // check sorting
  694. result, err = c.TxSearch(ctx, "tx.height >= 1", false, nil, nil, "asc")
  695. require.NoError(t, err)
  696. for k := 0; k < len(result.Txs)-1; k++ {
  697. require.LessOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height)
  698. require.LessOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index)
  699. }
  700. result, err = c.TxSearch(ctx, "tx.height >= 1", false, nil, nil, "desc")
  701. require.NoError(t, err)
  702. for k := 0; k < len(result.Txs)-1; k++ {
  703. require.GreaterOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height)
  704. require.GreaterOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index)
  705. }
  706. // check pagination
  707. perPage = 3
  708. var (
  709. seen = map[int64]bool{}
  710. maxHeight int64
  711. pages = int(math.Ceil(float64(txCount) / float64(perPage)))
  712. )
  713. for page := 1; page <= pages; page++ {
  714. page := page
  715. result, err := c.TxSearch(ctx, "tx.height >= 1", false, &page, &perPage, "asc")
  716. require.NoError(t, err)
  717. if page < pages {
  718. require.Len(t, result.Txs, perPage)
  719. } else {
  720. require.LessOrEqual(t, len(result.Txs), perPage)
  721. }
  722. require.Equal(t, txCount, result.TotalCount)
  723. for _, tx := range result.Txs {
  724. require.False(t, seen[tx.Height],
  725. "Found duplicate height %v in page %v", tx.Height, page)
  726. require.Greater(t, tx.Height, maxHeight,
  727. "Found decreasing height %v (max seen %v) in page %v", tx.Height, maxHeight, page)
  728. seen[tx.Height] = true
  729. maxHeight = tx.Height
  730. }
  731. }
  732. require.Len(t, seen, txCount)
  733. })
  734. }
  735. })
  736. }
  737. func testBatchedJSONRPCCalls(ctx context.Context, t *testing.T, c *rpchttp.HTTP) {
  738. k1, v1, tx1 := MakeTxKV()
  739. k2, v2, tx2 := MakeTxKV()
  740. batch := c.NewBatch()
  741. r1, err := batch.BroadcastTxCommit(ctx, tx1)
  742. require.NoError(t, err)
  743. r2, err := batch.BroadcastTxCommit(ctx, tx2)
  744. require.NoError(t, err)
  745. require.Equal(t, 2, batch.Count())
  746. bresults, err := batch.Send(ctx)
  747. require.NoError(t, err)
  748. require.Len(t, bresults, 2)
  749. require.Equal(t, 0, batch.Count())
  750. bresult1, ok := bresults[0].(*coretypes.ResultBroadcastTxCommit)
  751. require.True(t, ok)
  752. require.Equal(t, *bresult1, *r1)
  753. bresult2, ok := bresults[1].(*coretypes.ResultBroadcastTxCommit)
  754. require.True(t, ok)
  755. require.Equal(t, *bresult2, *r2)
  756. apph := tmmath.MaxInt64(bresult1.Height, bresult2.Height) + 1
  757. err = client.WaitForHeight(ctx, c, apph, nil)
  758. require.NoError(t, err)
  759. q1, err := batch.ABCIQuery(ctx, "/key", k1)
  760. require.NoError(t, err)
  761. q2, err := batch.ABCIQuery(ctx, "/key", k2)
  762. require.NoError(t, err)
  763. require.Equal(t, 2, batch.Count())
  764. qresults, err := batch.Send(ctx)
  765. require.NoError(t, err)
  766. require.Len(t, qresults, 2)
  767. require.Equal(t, 0, batch.Count())
  768. qresult1, ok := qresults[0].(*coretypes.ResultABCIQuery)
  769. require.True(t, ok)
  770. require.Equal(t, *qresult1, *q1)
  771. qresult2, ok := qresults[1].(*coretypes.ResultABCIQuery)
  772. require.True(t, ok)
  773. require.Equal(t, *qresult2, *q2)
  774. require.Equal(t, qresult1.Response.Key, k1)
  775. require.Equal(t, qresult2.Response.Key, k2)
  776. require.Equal(t, qresult1.Response.Value, v1)
  777. require.Equal(t, qresult2.Response.Value, v2)
  778. }