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.

934 lines
29 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. "fmt"
  7. "math"
  8. "net/http"
  9. "strings"
  10. "sync"
  11. "testing"
  12. "time"
  13. "github.com/stretchr/testify/assert"
  14. "github.com/stretchr/testify/require"
  15. abci "github.com/tendermint/tendermint/abci/types"
  16. "github.com/tendermint/tendermint/config"
  17. "github.com/tendermint/tendermint/crypto/ed25519"
  18. "github.com/tendermint/tendermint/crypto/encoding"
  19. "github.com/tendermint/tendermint/internal/mempool"
  20. rpccore "github.com/tendermint/tendermint/internal/rpc/core"
  21. tmjson "github.com/tendermint/tendermint/libs/json"
  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. c.Logger = logger
  39. t.Cleanup(func() {
  40. if c.IsRunning() {
  41. require.NoError(t, c.Stop())
  42. }
  43. })
  44. return c
  45. }
  46. func getHTTPClientWithTimeout(t *testing.T, logger log.Logger, conf *config.Config, timeout time.Duration) *rpchttp.HTTP {
  47. t.Helper()
  48. rpcAddr := conf.RPC.ListenAddress
  49. http.DefaultClient.Timeout = timeout
  50. c, err := rpchttp.NewWithClient(rpcAddr, http.DefaultClient)
  51. require.NoError(t, err)
  52. c.Logger = logger
  53. t.Cleanup(func() {
  54. http.DefaultClient.Timeout = 0
  55. if c.IsRunning() {
  56. require.NoError(t, c.Stop())
  57. }
  58. })
  59. return c
  60. }
  61. // GetClients returns a slice of clients for table-driven tests
  62. func GetClients(t *testing.T, ns service.Service, conf *config.Config) []client.Client {
  63. t.Helper()
  64. node, ok := ns.(rpclocal.NodeService)
  65. require.True(t, ok)
  66. logger := log.NewTestingLogger(t)
  67. ncl, err := rpclocal.New(logger, node)
  68. require.NoError(t, err)
  69. return []client.Client{
  70. ncl,
  71. getHTTPClient(t, logger, conf),
  72. }
  73. }
  74. func TestClientOperations(t *testing.T) {
  75. ctx, cancel := context.WithCancel(context.Background())
  76. defer cancel()
  77. logger := log.NewTestingLogger(t)
  78. _, conf := NodeSuite(t, logger)
  79. t.Run("NilCustomHTTPClient", func(t *testing.T) {
  80. _, err := rpchttp.NewWithClient("http://example.com", nil)
  81. require.Error(t, err)
  82. _, err = rpcclient.NewWithHTTPClient("http://example.com", nil)
  83. require.Error(t, err)
  84. })
  85. t.Run("ParseInvalidAddress", func(t *testing.T) {
  86. // should remove trailing /
  87. invalidRemote := conf.RPC.ListenAddress + "/"
  88. _, err := rpchttp.New(invalidRemote)
  89. require.NoError(t, err)
  90. })
  91. t.Run("CustomHTTPClient", func(t *testing.T) {
  92. remote := conf.RPC.ListenAddress
  93. c, err := rpchttp.NewWithClient(remote, http.DefaultClient)
  94. require.NoError(t, err)
  95. status, err := c.Status(ctx)
  96. require.NoError(t, err)
  97. require.NotNil(t, status)
  98. })
  99. t.Run("CorsEnabled", func(t *testing.T) {
  100. origin := conf.RPC.CORSAllowedOrigins[0]
  101. remote := strings.ReplaceAll(conf.RPC.ListenAddress, "tcp", "http")
  102. req, err := http.NewRequestWithContext(ctx, "GET", remote, nil)
  103. require.NoError(t, err, "%+v", err)
  104. req.Header.Set("Origin", origin)
  105. resp, err := http.DefaultClient.Do(req)
  106. require.NoError(t, err, "%+v", err)
  107. defer resp.Body.Close()
  108. assert.Equal(t, resp.Header.Get("Access-Control-Allow-Origin"), origin)
  109. })
  110. t.Run("Batching", func(t *testing.T) {
  111. t.Run("JSONRPCCalls", func(t *testing.T) {
  112. logger := log.NewTestingLogger(t)
  113. c := getHTTPClient(t, logger, conf)
  114. testBatchedJSONRPCCalls(ctx, t, c)
  115. })
  116. t.Run("JSONRPCCallsCancellation", func(t *testing.T) {
  117. _, _, tx1 := MakeTxKV()
  118. _, _, tx2 := MakeTxKV()
  119. logger := log.NewTestingLogger(t)
  120. c := getHTTPClient(t, logger, conf)
  121. batch := c.NewBatch()
  122. _, err := batch.BroadcastTxCommit(ctx, tx1)
  123. require.NoError(t, err)
  124. _, err = batch.BroadcastTxCommit(ctx, tx2)
  125. require.NoError(t, err)
  126. // we should have 2 requests waiting
  127. require.Equal(t, 2, batch.Count())
  128. // we want to make sure we cleared 2 pending requests
  129. require.Equal(t, 2, batch.Clear())
  130. // now there should be no batched requests
  131. require.Equal(t, 0, batch.Count())
  132. })
  133. t.Run("SendingEmptyRequest", func(t *testing.T) {
  134. logger := log.NewTestingLogger(t)
  135. c := getHTTPClient(t, logger, conf)
  136. batch := c.NewBatch()
  137. _, err := batch.Send(ctx)
  138. require.Error(t, err, "sending an empty batch of JSON RPC requests should result in an error")
  139. })
  140. t.Run("ClearingEmptyRequest", func(t *testing.T) {
  141. logger := log.NewTestingLogger(t)
  142. c := getHTTPClient(t, logger, conf)
  143. batch := c.NewBatch()
  144. require.Zero(t, batch.Clear(), "clearing an empty batch of JSON RPC requests should result in a 0 result")
  145. })
  146. t.Run("ConcurrentJSONRPC", func(t *testing.T) {
  147. logger := log.NewTestingLogger(t)
  148. var wg sync.WaitGroup
  149. c := getHTTPClient(t, logger, conf)
  150. for i := 0; i < 50; i++ {
  151. wg.Add(1)
  152. go func() {
  153. defer wg.Done()
  154. testBatchedJSONRPCCalls(ctx, t, c)
  155. }()
  156. }
  157. wg.Wait()
  158. })
  159. })
  160. t.Run("HTTPReturnsErrorIfClientIsNotRunning", func(t *testing.T) {
  161. logger := log.NewTestingLogger(t)
  162. c := getHTTPClientWithTimeout(t, logger, conf, 100*time.Millisecond)
  163. // on Subscribe
  164. _, err := c.Subscribe(ctx, "TestHeaderEvents",
  165. types.QueryForEvent(types.EventNewBlockHeaderValue).String())
  166. assert.Error(t, err)
  167. // on Unsubscribe
  168. err = c.Unsubscribe(ctx, "TestHeaderEvents",
  169. types.QueryForEvent(types.EventNewBlockHeaderValue).String())
  170. assert.Error(t, err)
  171. // on UnsubscribeAll
  172. err = c.UnsubscribeAll(ctx, "TestHeaderEvents")
  173. assert.Error(t, err)
  174. })
  175. }
  176. // Make sure info is correct (we connect properly)
  177. func TestClientMethodCalls(t *testing.T) {
  178. ctx, cancel := context.WithCancel(context.Background())
  179. defer cancel()
  180. logger := log.NewTestingLogger(t)
  181. n, conf := NodeSuite(t, logger)
  182. // for broadcast tx tests
  183. pool := getMempool(t, n)
  184. // for evidence tests
  185. pv, err := privval.LoadOrGenFilePV(conf.PrivValidator.KeyFile(), conf.PrivValidator.StateFile())
  186. require.NoError(t, err)
  187. for i, c := range GetClients(t, n, conf) {
  188. t.Run(fmt.Sprintf("%T", c), func(t *testing.T) {
  189. t.Run("Status", func(t *testing.T) {
  190. status, err := c.Status(ctx)
  191. require.NoError(t, err, "%d: %+v", i, err)
  192. assert.Equal(t, conf.Moniker, status.NodeInfo.Moniker)
  193. })
  194. t.Run("Info", func(t *testing.T) {
  195. info, err := c.ABCIInfo(ctx)
  196. require.NoError(t, err)
  197. status, err := c.Status(ctx)
  198. require.NoError(t, err)
  199. assert.GreaterOrEqual(t, status.SyncInfo.LatestBlockHeight, info.Response.LastBlockHeight)
  200. assert.True(t, strings.Contains(info.Response.Data, "size"))
  201. })
  202. t.Run("NetInfo", func(t *testing.T) {
  203. nc, ok := c.(client.NetworkClient)
  204. require.True(t, ok, "%d", i)
  205. netinfo, err := nc.NetInfo(ctx)
  206. require.NoError(t, err, "%d: %+v", i, err)
  207. assert.True(t, netinfo.Listening)
  208. assert.Equal(t, 0, len(netinfo.Peers))
  209. })
  210. t.Run("DumpConsensusState", func(t *testing.T) {
  211. // FIXME: fix server so it doesn't panic on invalid input
  212. nc, ok := c.(client.NetworkClient)
  213. require.True(t, ok, "%d", i)
  214. cons, err := nc.DumpConsensusState(ctx)
  215. require.NoError(t, err, "%d: %+v", i, err)
  216. assert.NotEmpty(t, cons.RoundState)
  217. assert.Empty(t, cons.Peers)
  218. })
  219. t.Run("ConsensusState", func(t *testing.T) {
  220. // FIXME: fix server so it doesn't panic on invalid input
  221. nc, ok := c.(client.NetworkClient)
  222. require.True(t, ok, "%d", i)
  223. cons, err := nc.ConsensusState(ctx)
  224. require.NoError(t, err, "%d: %+v", i, err)
  225. assert.NotEmpty(t, cons.RoundState)
  226. })
  227. t.Run("Health", func(t *testing.T) {
  228. nc, ok := c.(client.NetworkClient)
  229. require.True(t, ok, "%d", i)
  230. _, err := nc.Health(ctx)
  231. require.NoError(t, err, "%d: %+v", i, err)
  232. })
  233. t.Run("GenesisAndValidators", func(t *testing.T) {
  234. // make sure this is the right genesis file
  235. gen, err := c.Genesis(ctx)
  236. require.NoError(t, err, "%d: %+v", i, err)
  237. // get the genesis validator
  238. require.Equal(t, 1, len(gen.Genesis.Validators))
  239. gval := gen.Genesis.Validators[0]
  240. // get the current validators
  241. h := int64(1)
  242. vals, err := c.Validators(ctx, &h, nil, nil)
  243. require.NoError(t, err, "%d: %+v", i, err)
  244. require.Equal(t, 1, len(vals.Validators))
  245. require.Equal(t, 1, vals.Count)
  246. require.Equal(t, 1, vals.Total)
  247. val := vals.Validators[0]
  248. // make sure the current set is also the genesis set
  249. assert.Equal(t, gval.Power, val.VotingPower)
  250. assert.Equal(t, gval.PubKey, val.PubKey)
  251. })
  252. t.Run("GenesisChunked", func(t *testing.T) {
  253. first, err := c.GenesisChunked(ctx, 0)
  254. require.NoError(t, err)
  255. decoded := make([]string, 0, first.TotalChunks)
  256. for i := 0; i < first.TotalChunks; i++ {
  257. chunk, err := c.GenesisChunked(ctx, uint(i))
  258. require.NoError(t, err)
  259. data, err := base64.StdEncoding.DecodeString(chunk.Data)
  260. require.NoError(t, err)
  261. decoded = append(decoded, string(data))
  262. }
  263. doc := []byte(strings.Join(decoded, ""))
  264. var out types.GenesisDoc
  265. require.NoError(t, tmjson.Unmarshal(doc, &out),
  266. "first: %+v, doc: %s", first, string(doc))
  267. })
  268. t.Run("ABCIQuery", func(t *testing.T) {
  269. // write something
  270. k, v, tx := MakeTxKV()
  271. status, err := c.Status(ctx)
  272. require.NoError(t, err)
  273. _, err = c.BroadcastTxSync(ctx, tx)
  274. require.NoError(t, err, "%d: %+v", i, err)
  275. apph := status.SyncInfo.LatestBlockHeight + 2 // this is where the tx will be applied to the state
  276. // wait before querying
  277. err = client.WaitForHeight(ctx, c, apph, nil)
  278. require.NoError(t, err)
  279. res, err := c.ABCIQuery(ctx, "/key", k)
  280. qres := res.Response
  281. if assert.NoError(t, err) && assert.True(t, qres.IsOK()) {
  282. assert.EqualValues(t, v, qres.Value)
  283. }
  284. })
  285. t.Run("AppCalls", func(t *testing.T) {
  286. // get an offset of height to avoid racing and guessing
  287. s, err := c.Status(ctx)
  288. require.NoError(t, err)
  289. // sh is start height or status height
  290. sh := s.SyncInfo.LatestBlockHeight
  291. // look for the future
  292. h := sh + 20
  293. _, err = c.Block(ctx, &h)
  294. require.Error(t, err) // no block yet
  295. // write something
  296. k, v, tx := MakeTxKV()
  297. bres, err := c.BroadcastTxCommit(ctx, tx)
  298. require.NoError(t, err)
  299. require.True(t, bres.DeliverTx.IsOK())
  300. txh := bres.Height
  301. apph := txh + 1 // this is where the tx will be applied to the state
  302. // wait before querying
  303. err = client.WaitForHeight(ctx, c, apph, nil)
  304. require.NoError(t, err)
  305. _qres, err := c.ABCIQueryWithOptions(ctx, "/key", k, client.ABCIQueryOptions{Prove: false})
  306. require.NoError(t, err)
  307. qres := _qres.Response
  308. if assert.True(t, qres.IsOK()) {
  309. assert.Equal(t, k, qres.Key)
  310. assert.EqualValues(t, v, qres.Value)
  311. }
  312. // make sure we can lookup the tx with proof
  313. ptx, err := c.Tx(ctx, bres.Hash, true)
  314. require.NoError(t, err)
  315. assert.EqualValues(t, txh, ptx.Height)
  316. assert.EqualValues(t, tx, ptx.Tx)
  317. // and we can even check the block is added
  318. block, err := c.Block(ctx, &apph)
  319. require.NoError(t, err)
  320. appHash := block.Block.Header.AppHash
  321. assert.True(t, len(appHash) > 0)
  322. assert.EqualValues(t, apph, block.Block.Header.Height)
  323. blockByHash, err := c.BlockByHash(ctx, block.BlockID.Hash)
  324. require.NoError(t, err)
  325. require.Equal(t, block, blockByHash)
  326. // check that the header matches the block hash
  327. header, err := c.Header(ctx, &apph)
  328. require.NoError(t, err)
  329. require.Equal(t, block.Block.Header, *header.Header)
  330. headerByHash, err := c.HeaderByHash(ctx, block.BlockID.Hash)
  331. require.NoError(t, err)
  332. require.Equal(t, header, headerByHash)
  333. // now check the results
  334. blockResults, err := c.BlockResults(ctx, &txh)
  335. require.NoError(t, err, "%d: %+v", i, err)
  336. assert.Equal(t, txh, blockResults.Height)
  337. if assert.Equal(t, 1, len(blockResults.TxsResults)) {
  338. // check success code
  339. assert.EqualValues(t, 0, blockResults.TxsResults[0].Code)
  340. }
  341. // check blockchain info, now that we know there is info
  342. info, err := c.BlockchainInfo(ctx, apph, apph)
  343. require.NoError(t, err)
  344. assert.True(t, info.LastHeight >= apph)
  345. if assert.Equal(t, 1, len(info.BlockMetas)) {
  346. lastMeta := info.BlockMetas[0]
  347. assert.EqualValues(t, apph, lastMeta.Header.Height)
  348. blockData := block.Block
  349. assert.Equal(t, blockData.Header.AppHash, lastMeta.Header.AppHash)
  350. assert.Equal(t, block.BlockID, lastMeta.BlockID)
  351. }
  352. // and get the corresponding commit with the same apphash
  353. commit, err := c.Commit(ctx, &apph)
  354. require.NoError(t, err)
  355. cappHash := commit.Header.AppHash
  356. assert.Equal(t, appHash, cappHash)
  357. assert.NotNil(t, commit.Commit)
  358. // compare the commits (note Commit(2) has commit from Block(3))
  359. h = apph - 1
  360. commit2, err := c.Commit(ctx, &h)
  361. require.NoError(t, err)
  362. assert.Equal(t, block.Block.LastCommitHash, commit2.Commit.Hash())
  363. // and we got a proof that works!
  364. _pres, err := c.ABCIQueryWithOptions(ctx, "/key", k, client.ABCIQueryOptions{Prove: true})
  365. require.NoError(t, err)
  366. pres := _pres.Response
  367. assert.True(t, pres.IsOK())
  368. // XXX Test proof
  369. })
  370. t.Run("BlockchainInfo", func(t *testing.T) {
  371. ctx, cancel := context.WithCancel(context.Background())
  372. defer cancel()
  373. err := client.WaitForHeight(ctx, c, 10, nil)
  374. require.NoError(t, err)
  375. res, err := c.BlockchainInfo(ctx, 0, 0)
  376. require.NoError(t, err, "%d: %+v", i, err)
  377. assert.True(t, res.LastHeight > 0)
  378. assert.True(t, len(res.BlockMetas) > 0)
  379. res, err = c.BlockchainInfo(ctx, 1, 1)
  380. require.NoError(t, err, "%d: %+v", i, err)
  381. assert.True(t, res.LastHeight > 0)
  382. assert.True(t, len(res.BlockMetas) == 1)
  383. res, err = c.BlockchainInfo(ctx, 1, 10000)
  384. require.NoError(t, err, "%d: %+v", i, err)
  385. assert.True(t, res.LastHeight > 0)
  386. assert.True(t, len(res.BlockMetas) < 100)
  387. for _, m := range res.BlockMetas {
  388. assert.NotNil(t, m)
  389. }
  390. res, err = c.BlockchainInfo(ctx, 10000, 1)
  391. require.Error(t, err)
  392. assert.Nil(t, res)
  393. assert.Contains(t, err.Error(), "can't be greater than max")
  394. })
  395. t.Run("BroadcastTxCommit", func(t *testing.T) {
  396. _, _, tx := MakeTxKV()
  397. bres, err := c.BroadcastTxCommit(ctx, tx)
  398. require.NoError(t, err, "%d: %+v", i, err)
  399. require.True(t, bres.CheckTx.IsOK())
  400. require.True(t, bres.DeliverTx.IsOK())
  401. require.Equal(t, 0, pool.Size())
  402. })
  403. t.Run("BroadcastTxSync", func(t *testing.T) {
  404. _, _, tx := MakeTxKV()
  405. initMempoolSize := pool.Size()
  406. bres, err := c.BroadcastTxSync(ctx, tx)
  407. require.NoError(t, err, "%d: %+v", i, err)
  408. require.Equal(t, bres.Code, abci.CodeTypeOK) // FIXME
  409. require.Equal(t, initMempoolSize+1, pool.Size())
  410. txs := pool.ReapMaxTxs(len(tx))
  411. require.EqualValues(t, tx, txs[0])
  412. pool.Flush()
  413. })
  414. t.Run("CheckTx", func(t *testing.T) {
  415. _, _, tx := MakeTxKV()
  416. res, err := c.CheckTx(ctx, tx)
  417. require.NoError(t, err)
  418. assert.Equal(t, abci.CodeTypeOK, res.Code)
  419. assert.Equal(t, 0, pool.Size(), "mempool must be empty")
  420. })
  421. t.Run("Events", func(t *testing.T) {
  422. // start for this test it if it wasn't already running
  423. if !c.IsRunning() {
  424. ctx, cancel := context.WithCancel(ctx)
  425. defer cancel()
  426. // if so, then we start it, listen, and stop it.
  427. err := c.Start(ctx)
  428. require.NoError(t, err)
  429. }
  430. t.Run("Header", func(t *testing.T) {
  431. evt, err := client.WaitForOneEvent(c, types.EventNewBlockHeaderValue, waitForEventTimeout)
  432. require.NoError(t, err, "%d: %+v", i, err)
  433. _, ok := evt.(types.EventDataNewBlockHeader)
  434. require.True(t, ok, "%d: %#v", i, evt)
  435. // TODO: more checks...
  436. })
  437. t.Run("Block", func(t *testing.T) {
  438. const subscriber = "TestBlockEvents"
  439. eventCh, err := c.Subscribe(ctx, subscriber, types.QueryForEvent(types.EventNewBlockValue).String())
  440. require.NoError(t, err)
  441. t.Cleanup(func() {
  442. if err := c.UnsubscribeAll(ctx, subscriber); err != nil {
  443. t.Error(err)
  444. }
  445. })
  446. var firstBlockHeight int64
  447. for i := int64(0); i < 3; i++ {
  448. event := <-eventCh
  449. blockEvent, ok := event.Data.(types.EventDataNewBlock)
  450. require.True(t, ok)
  451. block := blockEvent.Block
  452. if firstBlockHeight == 0 {
  453. firstBlockHeight = block.Header.Height
  454. }
  455. require.Equal(t, firstBlockHeight+i, block.Header.Height)
  456. }
  457. })
  458. t.Run("BroadcastTxAsync", func(t *testing.T) {
  459. testTxEventsSent(ctx, t, "async", c)
  460. })
  461. t.Run("BroadcastTxSync", func(t *testing.T) {
  462. testTxEventsSent(ctx, t, "sync", c)
  463. })
  464. })
  465. t.Run("Evidence", func(t *testing.T) {
  466. t.Run("BraodcastDuplicateVote", func(t *testing.T) {
  467. ctx, cancel := context.WithCancel(context.Background())
  468. defer cancel()
  469. chainID := conf.ChainID()
  470. correct, fakes := makeEvidences(t, pv, chainID)
  471. // make sure that the node has produced enough blocks
  472. waitForBlock(ctx, t, c, 2)
  473. result, err := c.BroadcastEvidence(ctx, correct)
  474. require.NoError(t, err, "BroadcastEvidence(%s) failed", correct)
  475. assert.Equal(t, correct.Hash(), result.Hash, "expected result hash to match evidence hash")
  476. status, err := c.Status(ctx)
  477. require.NoError(t, err)
  478. err = client.WaitForHeight(ctx, c, status.SyncInfo.LatestBlockHeight+2, nil)
  479. require.NoError(t, err)
  480. ed25519pub := pv.Key.PubKey.(ed25519.PubKey)
  481. rawpub := ed25519pub.Bytes()
  482. result2, err := c.ABCIQuery(ctx, "/val", rawpub)
  483. require.NoError(t, err)
  484. qres := result2.Response
  485. require.True(t, qres.IsOK())
  486. var v abci.ValidatorUpdate
  487. err = abci.ReadMessage(bytes.NewReader(qres.Value), &v)
  488. require.NoError(t, err, "Error reading query result, value %v", qres.Value)
  489. pk, err := encoding.PubKeyFromProto(v.PubKey)
  490. require.NoError(t, err)
  491. require.EqualValues(t, rawpub, pk, "Stored PubKey not equal with expected, value %v", string(qres.Value))
  492. require.Equal(t, int64(9), v.Power, "Stored Power not equal with expected, value %v", string(qres.Value))
  493. for _, fake := range fakes {
  494. _, err := c.BroadcastEvidence(ctx, fake)
  495. require.Error(t, err, "BroadcastEvidence(%s) succeeded, but the evidence was fake", fake)
  496. }
  497. })
  498. t.Run("BroadcastEmpty", func(t *testing.T) {
  499. _, err := c.BroadcastEvidence(ctx, nil)
  500. assert.Error(t, err)
  501. })
  502. })
  503. })
  504. }
  505. }
  506. func getMempool(t *testing.T, srv service.Service) mempool.Mempool {
  507. t.Helper()
  508. n, ok := srv.(interface {
  509. RPCEnvironment() *rpccore.Environment
  510. })
  511. require.True(t, ok)
  512. return n.RPCEnvironment().Mempool
  513. }
  514. // these cases are roughly the same as the TestClientMethodCalls, but
  515. // they have to loop over their clients in the individual test cases,
  516. // so making a separate suite makes more sense, though isn't strictly
  517. // speaking desirable.
  518. func TestClientMethodCallsAdvanced(t *testing.T) {
  519. ctx, cancel := context.WithCancel(context.Background())
  520. defer cancel()
  521. logger := log.NewTestingLogger(t)
  522. n, conf := NodeSuite(t, logger)
  523. pool := getMempool(t, n)
  524. t.Run("UnconfirmedTxs", func(t *testing.T) {
  525. // populate mempool with 5 tx
  526. txs := make([]types.Tx, 5)
  527. ch := make(chan error, 5)
  528. for i := 0; i < 5; i++ {
  529. _, _, tx := MakeTxKV()
  530. txs[i] = tx
  531. err := pool.CheckTx(ctx, tx, func(_ *abci.Response) { ch <- nil }, mempool.TxInfo{})
  532. require.NoError(t, err)
  533. }
  534. // wait for tx to arrive in mempoool.
  535. for i := 0; i < 5; i++ {
  536. select {
  537. case <-ch:
  538. case <-time.After(5 * time.Second):
  539. t.Error("Timed out waiting for CheckTx callback")
  540. }
  541. }
  542. close(ch)
  543. for _, c := range GetClients(t, n, conf) {
  544. for i := 1; i <= 2; i++ {
  545. mc := c.(client.MempoolClient)
  546. page, perPage := i, 3
  547. res, err := mc.UnconfirmedTxs(ctx, &page, &perPage)
  548. require.NoError(t, err)
  549. if i == 2 {
  550. perPage = 2
  551. }
  552. assert.Equal(t, perPage, res.Count)
  553. assert.Equal(t, 5, res.Total)
  554. assert.Equal(t, pool.SizeBytes(), res.TotalBytes)
  555. for _, tx := range res.Txs {
  556. assert.Contains(t, txs, tx)
  557. }
  558. }
  559. }
  560. pool.Flush()
  561. })
  562. t.Run("NumUnconfirmedTxs", func(t *testing.T) {
  563. ch := make(chan struct{})
  564. pool := getMempool(t, n)
  565. _, _, tx := MakeTxKV()
  566. err := pool.CheckTx(ctx, tx, func(_ *abci.Response) { close(ch) }, mempool.TxInfo{})
  567. require.NoError(t, err)
  568. // wait for tx to arrive in mempoool.
  569. select {
  570. case <-ch:
  571. case <-time.After(5 * time.Second):
  572. t.Error("Timed out waiting for CheckTx callback")
  573. }
  574. mempoolSize := pool.Size()
  575. for i, c := range GetClients(t, n, conf) {
  576. mc, ok := c.(client.MempoolClient)
  577. require.True(t, ok, "%d", i)
  578. res, err := mc.NumUnconfirmedTxs(ctx)
  579. require.NoError(t, err, "%d: %+v", i, err)
  580. assert.Equal(t, mempoolSize, res.Count)
  581. assert.Equal(t, mempoolSize, res.Total)
  582. assert.Equal(t, pool.SizeBytes(), res.TotalBytes)
  583. }
  584. pool.Flush()
  585. })
  586. t.Run("Tx", func(t *testing.T) {
  587. logger := log.NewTestingLogger(t)
  588. c := getHTTPClient(t, logger, conf)
  589. // first we broadcast a tx
  590. _, _, tx := MakeTxKV()
  591. bres, err := c.BroadcastTxCommit(ctx, tx)
  592. require.NoError(t, err, "%+v", err)
  593. txHeight := bres.Height
  594. txHash := bres.Hash
  595. anotherTxHash := types.Tx("a different tx").Hash()
  596. cases := []struct {
  597. valid bool
  598. prove bool
  599. hash []byte
  600. }{
  601. // only valid if correct hash provided
  602. {true, false, txHash},
  603. {true, true, txHash},
  604. {false, false, anotherTxHash},
  605. {false, true, anotherTxHash},
  606. {false, false, nil},
  607. {false, true, nil},
  608. }
  609. for _, c := range GetClients(t, n, conf) {
  610. t.Run(fmt.Sprintf("%T", c), func(t *testing.T) {
  611. for j, tc := range cases {
  612. t.Run(fmt.Sprintf("Case%d", j), func(t *testing.T) {
  613. // now we query for the tx.
  614. // since there's only one tx, we know index=0.
  615. ptx, err := c.Tx(ctx, tc.hash, tc.prove)
  616. if !tc.valid {
  617. require.Error(t, err)
  618. } else {
  619. require.NoError(t, err, "%+v", err)
  620. assert.EqualValues(t, txHeight, ptx.Height)
  621. assert.EqualValues(t, tx, ptx.Tx)
  622. assert.Zero(t, ptx.Index)
  623. assert.True(t, ptx.TxResult.IsOK())
  624. assert.EqualValues(t, txHash, ptx.Hash)
  625. // time to verify the proof
  626. proof := ptx.Proof
  627. if tc.prove && assert.EqualValues(t, tx, proof.Data) {
  628. assert.NoError(t, proof.Proof.Verify(proof.RootHash, txHash))
  629. }
  630. }
  631. })
  632. }
  633. })
  634. }
  635. })
  636. t.Run("TxSearchWithTimeout", func(t *testing.T) {
  637. logger := log.NewTestingLogger(t)
  638. timeoutClient := getHTTPClientWithTimeout(t, logger, conf, 10*time.Second)
  639. _, _, tx := MakeTxKV()
  640. _, err := timeoutClient.BroadcastTxCommit(ctx, tx)
  641. require.NoError(t, err)
  642. // query using a compositeKey (see kvstore application)
  643. result, err := timeoutClient.TxSearch(ctx, "app.creator='Cosmoshi Netowoko'", false, nil, nil, "asc")
  644. require.NoError(t, err)
  645. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  646. })
  647. t.Run("TxSearch", func(t *testing.T) {
  648. t.Skip("Test Asserts Non-Deterministic Results")
  649. logger := log.NewTestingLogger(t)
  650. c := getHTTPClient(t, logger, conf)
  651. // first we broadcast a few txs
  652. for i := 0; i < 10; i++ {
  653. _, _, tx := MakeTxKV()
  654. _, err := c.BroadcastTxSync(ctx, tx)
  655. require.NoError(t, err)
  656. }
  657. // since we're not using an isolated test server, we'll have lingering transactions
  658. // from other tests as well
  659. result, err := c.TxSearch(ctx, "tx.height >= 0", true, nil, nil, "asc")
  660. require.NoError(t, err)
  661. txCount := len(result.Txs)
  662. // pick out the last tx to have something to search for in tests
  663. find := result.Txs[len(result.Txs)-1]
  664. anotherTxHash := types.Tx("a different tx").Hash()
  665. for _, c := range GetClients(t, n, conf) {
  666. t.Run(fmt.Sprintf("%T", c), func(t *testing.T) {
  667. // now we query for the tx.
  668. result, err := c.TxSearch(ctx, fmt.Sprintf("tx.hash='%v'", find.Hash), true, nil, nil, "asc")
  669. require.NoError(t, err)
  670. require.Len(t, result.Txs, 1)
  671. require.Equal(t, find.Hash, result.Txs[0].Hash)
  672. ptx := result.Txs[0]
  673. assert.EqualValues(t, find.Height, ptx.Height)
  674. assert.EqualValues(t, find.Tx, ptx.Tx)
  675. assert.Zero(t, ptx.Index)
  676. assert.True(t, ptx.TxResult.IsOK())
  677. assert.EqualValues(t, find.Hash, ptx.Hash)
  678. // time to verify the proof
  679. if assert.EqualValues(t, find.Tx, ptx.Proof.Data) {
  680. assert.NoError(t, ptx.Proof.Proof.Verify(ptx.Proof.RootHash, find.Hash))
  681. }
  682. // query by height
  683. result, err = c.TxSearch(ctx, fmt.Sprintf("tx.height=%d", find.Height), true, nil, nil, "asc")
  684. require.NoError(t, err)
  685. require.Len(t, result.Txs, 1)
  686. // query for non existing tx
  687. result, err = c.TxSearch(ctx, fmt.Sprintf("tx.hash='%X'", anotherTxHash), false, nil, nil, "asc")
  688. require.NoError(t, err)
  689. require.Len(t, result.Txs, 0)
  690. // query using a compositeKey (see kvstore application)
  691. result, err = c.TxSearch(ctx, "app.creator='Cosmoshi Netowoko'", false, nil, nil, "asc")
  692. require.NoError(t, err)
  693. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  694. // query using an index key
  695. result, err = c.TxSearch(ctx, "app.index_key='index is working'", false, nil, nil, "asc")
  696. require.NoError(t, err)
  697. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  698. // query using an noindex key
  699. result, err = c.TxSearch(ctx, "app.noindex_key='index is working'", false, nil, nil, "asc")
  700. require.NoError(t, err)
  701. require.Equal(t, len(result.Txs), 0, "expected a lot of transactions")
  702. // query using a compositeKey (see kvstore application) and height
  703. result, err = c.TxSearch(ctx,
  704. "app.creator='Cosmoshi Netowoko' AND tx.height<10000", true, nil, nil, "asc")
  705. require.NoError(t, err)
  706. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  707. // query a non existing tx with page 1 and txsPerPage 1
  708. perPage := 1
  709. result, err = c.TxSearch(ctx, "app.creator='Cosmoshi Neetowoko'", true, nil, &perPage, "asc")
  710. require.NoError(t, err)
  711. require.Len(t, result.Txs, 0)
  712. // check sorting
  713. result, err = c.TxSearch(ctx, "tx.height >= 1", false, nil, nil, "asc")
  714. require.NoError(t, err)
  715. for k := 0; k < len(result.Txs)-1; k++ {
  716. require.LessOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height)
  717. require.LessOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index)
  718. }
  719. result, err = c.TxSearch(ctx, "tx.height >= 1", false, nil, nil, "desc")
  720. require.NoError(t, err)
  721. for k := 0; k < len(result.Txs)-1; k++ {
  722. require.GreaterOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height)
  723. require.GreaterOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index)
  724. }
  725. // check pagination
  726. perPage = 3
  727. var (
  728. seen = map[int64]bool{}
  729. maxHeight int64
  730. pages = int(math.Ceil(float64(txCount) / float64(perPage)))
  731. )
  732. for page := 1; page <= pages; page++ {
  733. page := page
  734. result, err := c.TxSearch(ctx, "tx.height >= 1", false, &page, &perPage, "asc")
  735. require.NoError(t, err)
  736. if page < pages {
  737. require.Len(t, result.Txs, perPage)
  738. } else {
  739. require.LessOrEqual(t, len(result.Txs), perPage)
  740. }
  741. require.Equal(t, txCount, result.TotalCount)
  742. for _, tx := range result.Txs {
  743. require.False(t, seen[tx.Height],
  744. "Found duplicate height %v in page %v", tx.Height, page)
  745. require.Greater(t, tx.Height, maxHeight,
  746. "Found decreasing height %v (max seen %v) in page %v", tx.Height, maxHeight, page)
  747. seen[tx.Height] = true
  748. maxHeight = tx.Height
  749. }
  750. }
  751. require.Len(t, seen, txCount)
  752. })
  753. }
  754. })
  755. }
  756. func testBatchedJSONRPCCalls(ctx context.Context, t *testing.T, c *rpchttp.HTTP) {
  757. k1, v1, tx1 := MakeTxKV()
  758. k2, v2, tx2 := MakeTxKV()
  759. batch := c.NewBatch()
  760. r1, err := batch.BroadcastTxCommit(ctx, tx1)
  761. require.NoError(t, err)
  762. r2, err := batch.BroadcastTxCommit(ctx, tx2)
  763. require.NoError(t, err)
  764. require.Equal(t, 2, batch.Count())
  765. bresults, err := batch.Send(ctx)
  766. require.NoError(t, err)
  767. require.Len(t, bresults, 2)
  768. require.Equal(t, 0, batch.Count())
  769. bresult1, ok := bresults[0].(*coretypes.ResultBroadcastTxCommit)
  770. require.True(t, ok)
  771. require.Equal(t, *bresult1, *r1)
  772. bresult2, ok := bresults[1].(*coretypes.ResultBroadcastTxCommit)
  773. require.True(t, ok)
  774. require.Equal(t, *bresult2, *r2)
  775. apph := tmmath.MaxInt64(bresult1.Height, bresult2.Height) + 1
  776. err = client.WaitForHeight(ctx, c, apph, nil)
  777. require.NoError(t, err)
  778. q1, err := batch.ABCIQuery(ctx, "/key", k1)
  779. require.NoError(t, err)
  780. q2, err := batch.ABCIQuery(ctx, "/key", k2)
  781. require.NoError(t, err)
  782. require.Equal(t, 2, batch.Count())
  783. qresults, err := batch.Send(ctx)
  784. require.NoError(t, err)
  785. require.Len(t, qresults, 2)
  786. require.Equal(t, 0, batch.Count())
  787. qresult1, ok := qresults[0].(*coretypes.ResultABCIQuery)
  788. require.True(t, ok)
  789. require.Equal(t, *qresult1, *q1)
  790. qresult2, ok := qresults[1].(*coretypes.ResultABCIQuery)
  791. require.True(t, ok)
  792. require.Equal(t, *qresult2, *q2)
  793. require.Equal(t, qresult1.Response.Key, k1)
  794. require.Equal(t, qresult2.Response.Key, k2)
  795. require.Equal(t, qresult1.Response.Value, v1)
  796. require.Equal(t, qresult2.Response.Value, v2)
  797. }