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.

936 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
6 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) ```
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
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) ```
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) ```
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
6 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
6 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
6 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
6 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
6 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
6 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
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
6 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
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
6 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
6 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
6 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
6 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
6 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
6 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
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
6 years ago
cleanup: Reduce and normalize import path aliasing. (#6975) The code in the Tendermint repository makes heavy use of import aliasing. This is made necessary by our extensive reuse of common base package names, and by repetition of similar names across different subdirectories. Unfortunately we have not been very consistent about which packages we alias in various circumstances, and the aliases we use vary. In the spirit of the advice in the style guide and https://github.com/golang/go/wiki/CodeReviewComments#imports, his change makes an effort to clean up and normalize import aliasing. This change makes no API or behavioral changes. It is a pure cleanup intended o help make the code more readable to developers (including myself) trying to understand what is being imported where. Only unexported names have been modified, and the changes were generated and applied mechanically with gofmt -r and comby, respecting the lexical and syntactic rules of Go. Even so, I did not fix every inconsistency. Where the changes would be too disruptive, I left it alone. The principles I followed in this cleanup are: - Remove aliases that restate the package name. - Remove aliases where the base package name is unambiguous. - Move overly-terse abbreviations from the import to the usage site. - Fix lexical issues (remove underscores, remove capitalization). - Fix import groupings to more closely match the style guide. - Group blank (side-effecting) imports and ensure they are commented. - Add aliases to multiple imports with the same base package name.
3 years ago
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
6 years ago
  1. package client_test
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/base64"
  6. "encoding/json"
  7. "fmt"
  8. "math"
  9. "net/http"
  10. "strings"
  11. "sync"
  12. "testing"
  13. "time"
  14. "github.com/stretchr/testify/assert"
  15. "github.com/stretchr/testify/require"
  16. abci "github.com/tendermint/tendermint/abci/types"
  17. "github.com/tendermint/tendermint/config"
  18. "github.com/tendermint/tendermint/crypto/ed25519"
  19. "github.com/tendermint/tendermint/crypto/encoding"
  20. "github.com/tendermint/tendermint/internal/mempool"
  21. rpccore "github.com/tendermint/tendermint/internal/rpc/core"
  22. "github.com/tendermint/tendermint/libs/log"
  23. tmmath "github.com/tendermint/tendermint/libs/math"
  24. "github.com/tendermint/tendermint/libs/service"
  25. "github.com/tendermint/tendermint/privval"
  26. "github.com/tendermint/tendermint/rpc/client"
  27. rpchttp "github.com/tendermint/tendermint/rpc/client/http"
  28. rpclocal "github.com/tendermint/tendermint/rpc/client/local"
  29. "github.com/tendermint/tendermint/rpc/coretypes"
  30. rpcclient "github.com/tendermint/tendermint/rpc/jsonrpc/client"
  31. "github.com/tendermint/tendermint/types"
  32. )
  33. func getHTTPClient(t *testing.T, logger log.Logger, conf *config.Config) *rpchttp.HTTP {
  34. t.Helper()
  35. rpcAddr := conf.RPC.ListenAddress
  36. c, err := rpchttp.NewWithClient(rpcAddr, http.DefaultClient)
  37. require.NoError(t, err)
  38. 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, json.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. // make sure that the node has produced enough blocks
  471. waitForBlock(ctx, t, c, 2)
  472. evidenceHeight := int64(1)
  473. block, _ := c.Block(ctx, &evidenceHeight)
  474. ts := block.Block.Time
  475. correct, fakes := makeEvidences(t, pv, chainID, ts)
  476. result, err := c.BroadcastEvidence(ctx, correct)
  477. require.NoError(t, err, "BroadcastEvidence(%s) failed", correct)
  478. assert.Equal(t, correct.Hash(), result.Hash, "expected result hash to match evidence hash")
  479. status, err := c.Status(ctx)
  480. require.NoError(t, err)
  481. err = client.WaitForHeight(ctx, c, status.SyncInfo.LatestBlockHeight+2, nil)
  482. require.NoError(t, err)
  483. ed25519pub := pv.Key.PubKey.(ed25519.PubKey)
  484. rawpub := ed25519pub.Bytes()
  485. result2, err := c.ABCIQuery(ctx, "/val", rawpub)
  486. require.NoError(t, err)
  487. qres := result2.Response
  488. require.True(t, qres.IsOK())
  489. var v abci.ValidatorUpdate
  490. err = abci.ReadMessage(bytes.NewReader(qres.Value), &v)
  491. require.NoError(t, err, "Error reading query result, value %v", qres.Value)
  492. pk, err := encoding.PubKeyFromProto(v.PubKey)
  493. require.NoError(t, err)
  494. require.EqualValues(t, rawpub, pk, "Stored PubKey not equal with expected, value %v", string(qres.Value))
  495. require.Equal(t, int64(9), v.Power, "Stored Power not equal with expected, value %v", string(qres.Value))
  496. for _, fake := range fakes {
  497. _, err := c.BroadcastEvidence(ctx, fake)
  498. require.Error(t, err, "BroadcastEvidence(%s) succeeded, but the evidence was fake", fake)
  499. }
  500. })
  501. t.Run("BroadcastEmpty", func(t *testing.T) {
  502. _, err := c.BroadcastEvidence(ctx, nil)
  503. require.Error(t, err)
  504. })
  505. })
  506. })
  507. }
  508. }
  509. func getMempool(t *testing.T, srv service.Service) mempool.Mempool {
  510. t.Helper()
  511. n, ok := srv.(interface {
  512. RPCEnvironment() *rpccore.Environment
  513. })
  514. require.True(t, ok)
  515. return n.RPCEnvironment().Mempool
  516. }
  517. // these cases are roughly the same as the TestClientMethodCalls, but
  518. // they have to loop over their clients in the individual test cases,
  519. // so making a separate suite makes more sense, though isn't strictly
  520. // speaking desirable.
  521. func TestClientMethodCallsAdvanced(t *testing.T) {
  522. ctx, cancel := context.WithCancel(context.Background())
  523. defer cancel()
  524. logger := log.NewTestingLogger(t)
  525. n, conf := NodeSuite(t, logger)
  526. pool := getMempool(t, n)
  527. t.Run("UnconfirmedTxs", func(t *testing.T) {
  528. // populate mempool with 5 tx
  529. txs := make([]types.Tx, 5)
  530. ch := make(chan error, 5)
  531. for i := 0; i < 5; i++ {
  532. _, _, tx := MakeTxKV()
  533. txs[i] = tx
  534. err := pool.CheckTx(ctx, tx, func(_ *abci.Response) { ch <- nil }, mempool.TxInfo{})
  535. require.NoError(t, err)
  536. }
  537. // wait for tx to arrive in mempoool.
  538. for i := 0; i < 5; i++ {
  539. select {
  540. case <-ch:
  541. case <-time.After(5 * time.Second):
  542. t.Error("Timed out waiting for CheckTx callback")
  543. }
  544. }
  545. close(ch)
  546. for _, c := range GetClients(t, n, conf) {
  547. for i := 1; i <= 2; i++ {
  548. mc := c.(client.MempoolClient)
  549. page, perPage := i, 3
  550. res, err := mc.UnconfirmedTxs(ctx, &page, &perPage)
  551. require.NoError(t, err)
  552. if i == 2 {
  553. perPage = 2
  554. }
  555. assert.Equal(t, perPage, res.Count)
  556. assert.Equal(t, 5, res.Total)
  557. assert.Equal(t, pool.SizeBytes(), res.TotalBytes)
  558. for _, tx := range res.Txs {
  559. assert.Contains(t, txs, tx)
  560. }
  561. }
  562. }
  563. pool.Flush()
  564. })
  565. t.Run("NumUnconfirmedTxs", func(t *testing.T) {
  566. ch := make(chan struct{})
  567. pool := getMempool(t, n)
  568. _, _, tx := MakeTxKV()
  569. err := pool.CheckTx(ctx, tx, func(_ *abci.Response) { close(ch) }, mempool.TxInfo{})
  570. require.NoError(t, err)
  571. // wait for tx to arrive in mempoool.
  572. select {
  573. case <-ch:
  574. case <-time.After(5 * time.Second):
  575. t.Error("Timed out waiting for CheckTx callback")
  576. }
  577. mempoolSize := pool.Size()
  578. for i, c := range GetClients(t, n, conf) {
  579. mc, ok := c.(client.MempoolClient)
  580. require.True(t, ok, "%d", i)
  581. res, err := mc.NumUnconfirmedTxs(ctx)
  582. require.NoError(t, err, "%d: %+v", i, err)
  583. assert.Equal(t, mempoolSize, res.Count)
  584. assert.Equal(t, mempoolSize, res.Total)
  585. assert.Equal(t, pool.SizeBytes(), res.TotalBytes)
  586. }
  587. pool.Flush()
  588. })
  589. t.Run("Tx", func(t *testing.T) {
  590. logger := log.NewTestingLogger(t)
  591. c := getHTTPClient(t, logger, conf)
  592. // first we broadcast a tx
  593. _, _, tx := MakeTxKV()
  594. bres, err := c.BroadcastTxCommit(ctx, tx)
  595. require.NoError(t, err, "%+v", err)
  596. txHeight := bres.Height
  597. txHash := bres.Hash
  598. anotherTxHash := types.Tx("a different tx").Hash()
  599. cases := []struct {
  600. valid bool
  601. prove bool
  602. hash []byte
  603. }{
  604. // only valid if correct hash provided
  605. {true, false, txHash},
  606. {true, true, txHash},
  607. {false, false, anotherTxHash},
  608. {false, true, anotherTxHash},
  609. {false, false, nil},
  610. {false, true, nil},
  611. }
  612. for _, c := range GetClients(t, n, conf) {
  613. t.Run(fmt.Sprintf("%T", c), func(t *testing.T) {
  614. for j, tc := range cases {
  615. t.Run(fmt.Sprintf("Case%d", j), func(t *testing.T) {
  616. // now we query for the tx.
  617. // since there's only one tx, we know index=0.
  618. ptx, err := c.Tx(ctx, tc.hash, tc.prove)
  619. if !tc.valid {
  620. require.Error(t, err)
  621. } else {
  622. require.NoError(t, err, "%+v", err)
  623. assert.EqualValues(t, txHeight, ptx.Height)
  624. assert.EqualValues(t, tx, ptx.Tx)
  625. assert.Zero(t, ptx.Index)
  626. assert.True(t, ptx.TxResult.IsOK())
  627. assert.EqualValues(t, txHash, ptx.Hash)
  628. // time to verify the proof
  629. proof := ptx.Proof
  630. if tc.prove && assert.EqualValues(t, tx, proof.Data) {
  631. assert.NoError(t, proof.Proof.Verify(proof.RootHash, txHash))
  632. }
  633. }
  634. })
  635. }
  636. })
  637. }
  638. })
  639. t.Run("TxSearchWithTimeout", func(t *testing.T) {
  640. logger := log.NewTestingLogger(t)
  641. timeoutClient := getHTTPClientWithTimeout(t, logger, conf, 10*time.Second)
  642. _, _, tx := MakeTxKV()
  643. _, err := timeoutClient.BroadcastTxCommit(ctx, tx)
  644. require.NoError(t, err)
  645. // query using a compositeKey (see kvstore application)
  646. result, err := timeoutClient.TxSearch(ctx, "app.creator='Cosmoshi Netowoko'", false, nil, nil, "asc")
  647. require.NoError(t, err)
  648. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  649. })
  650. t.Run("TxSearch", func(t *testing.T) {
  651. t.Skip("Test Asserts Non-Deterministic Results")
  652. logger := log.NewTestingLogger(t)
  653. c := getHTTPClient(t, logger, conf)
  654. // first we broadcast a few txs
  655. for i := 0; i < 10; i++ {
  656. _, _, tx := MakeTxKV()
  657. _, err := c.BroadcastTxSync(ctx, tx)
  658. require.NoError(t, err)
  659. }
  660. // since we're not using an isolated test server, we'll have lingering transactions
  661. // from other tests as well
  662. result, err := c.TxSearch(ctx, "tx.height >= 0", true, nil, nil, "asc")
  663. require.NoError(t, err)
  664. txCount := len(result.Txs)
  665. // pick out the last tx to have something to search for in tests
  666. find := result.Txs[len(result.Txs)-1]
  667. anotherTxHash := types.Tx("a different tx").Hash()
  668. for _, c := range GetClients(t, n, conf) {
  669. t.Run(fmt.Sprintf("%T", c), func(t *testing.T) {
  670. // now we query for the tx.
  671. result, err := c.TxSearch(ctx, fmt.Sprintf("tx.hash='%v'", find.Hash), true, nil, nil, "asc")
  672. require.NoError(t, err)
  673. require.Len(t, result.Txs, 1)
  674. require.Equal(t, find.Hash, result.Txs[0].Hash)
  675. ptx := result.Txs[0]
  676. assert.EqualValues(t, find.Height, ptx.Height)
  677. assert.EqualValues(t, find.Tx, ptx.Tx)
  678. assert.Zero(t, ptx.Index)
  679. assert.True(t, ptx.TxResult.IsOK())
  680. assert.EqualValues(t, find.Hash, ptx.Hash)
  681. // time to verify the proof
  682. if assert.EqualValues(t, find.Tx, ptx.Proof.Data) {
  683. assert.NoError(t, ptx.Proof.Proof.Verify(ptx.Proof.RootHash, find.Hash))
  684. }
  685. // query by height
  686. result, err = c.TxSearch(ctx, fmt.Sprintf("tx.height=%d", find.Height), true, nil, nil, "asc")
  687. require.NoError(t, err)
  688. require.Len(t, result.Txs, 1)
  689. // query for non existing tx
  690. result, err = c.TxSearch(ctx, fmt.Sprintf("tx.hash='%X'", anotherTxHash), false, nil, nil, "asc")
  691. require.NoError(t, err)
  692. require.Len(t, result.Txs, 0)
  693. // query using a compositeKey (see kvstore application)
  694. result, err = c.TxSearch(ctx, "app.creator='Cosmoshi Netowoko'", false, nil, nil, "asc")
  695. require.NoError(t, err)
  696. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  697. // query using an index key
  698. result, err = c.TxSearch(ctx, "app.index_key='index is working'", false, nil, nil, "asc")
  699. require.NoError(t, err)
  700. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  701. // query using an noindex key
  702. result, err = c.TxSearch(ctx, "app.noindex_key='index is working'", false, nil, nil, "asc")
  703. require.NoError(t, err)
  704. require.Equal(t, len(result.Txs), 0, "expected a lot of transactions")
  705. // query using a compositeKey (see kvstore application) and height
  706. result, err = c.TxSearch(ctx,
  707. "app.creator='Cosmoshi Netowoko' AND tx.height<10000", true, nil, nil, "asc")
  708. require.NoError(t, err)
  709. require.Greater(t, len(result.Txs), 0, "expected a lot of transactions")
  710. // query a non existing tx with page 1 and txsPerPage 1
  711. perPage := 1
  712. result, err = c.TxSearch(ctx, "app.creator='Cosmoshi Neetowoko'", true, nil, &perPage, "asc")
  713. require.NoError(t, err)
  714. require.Len(t, result.Txs, 0)
  715. // check sorting
  716. result, err = c.TxSearch(ctx, "tx.height >= 1", false, nil, nil, "asc")
  717. require.NoError(t, err)
  718. for k := 0; k < len(result.Txs)-1; k++ {
  719. require.LessOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height)
  720. require.LessOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index)
  721. }
  722. result, err = c.TxSearch(ctx, "tx.height >= 1", false, nil, nil, "desc")
  723. require.NoError(t, err)
  724. for k := 0; k < len(result.Txs)-1; k++ {
  725. require.GreaterOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height)
  726. require.GreaterOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index)
  727. }
  728. // check pagination
  729. perPage = 3
  730. var (
  731. seen = map[int64]bool{}
  732. maxHeight int64
  733. pages = int(math.Ceil(float64(txCount) / float64(perPage)))
  734. )
  735. for page := 1; page <= pages; page++ {
  736. page := page
  737. result, err := c.TxSearch(ctx, "tx.height >= 1", false, &page, &perPage, "asc")
  738. require.NoError(t, err)
  739. if page < pages {
  740. require.Len(t, result.Txs, perPage)
  741. } else {
  742. require.LessOrEqual(t, len(result.Txs), perPage)
  743. }
  744. require.Equal(t, txCount, result.TotalCount)
  745. for _, tx := range result.Txs {
  746. require.False(t, seen[tx.Height],
  747. "Found duplicate height %v in page %v", tx.Height, page)
  748. require.Greater(t, tx.Height, maxHeight,
  749. "Found decreasing height %v (max seen %v) in page %v", tx.Height, maxHeight, page)
  750. seen[tx.Height] = true
  751. maxHeight = tx.Height
  752. }
  753. }
  754. require.Len(t, seen, txCount)
  755. })
  756. }
  757. })
  758. }
  759. func testBatchedJSONRPCCalls(ctx context.Context, t *testing.T, c *rpchttp.HTTP) {
  760. k1, v1, tx1 := MakeTxKV()
  761. k2, v2, tx2 := MakeTxKV()
  762. batch := c.NewBatch()
  763. r1, err := batch.BroadcastTxCommit(ctx, tx1)
  764. require.NoError(t, err)
  765. r2, err := batch.BroadcastTxCommit(ctx, tx2)
  766. require.NoError(t, err)
  767. require.Equal(t, 2, batch.Count())
  768. bresults, err := batch.Send(ctx)
  769. require.NoError(t, err)
  770. require.Len(t, bresults, 2)
  771. require.Equal(t, 0, batch.Count())
  772. bresult1, ok := bresults[0].(*coretypes.ResultBroadcastTxCommit)
  773. require.True(t, ok)
  774. require.Equal(t, *bresult1, *r1)
  775. bresult2, ok := bresults[1].(*coretypes.ResultBroadcastTxCommit)
  776. require.True(t, ok)
  777. require.Equal(t, *bresult2, *r2)
  778. apph := tmmath.MaxInt64(bresult1.Height, bresult2.Height) + 1
  779. err = client.WaitForHeight(ctx, c, apph, nil)
  780. require.NoError(t, err)
  781. q1, err := batch.ABCIQuery(ctx, "/key", k1)
  782. require.NoError(t, err)
  783. q2, err := batch.ABCIQuery(ctx, "/key", k2)
  784. require.NoError(t, err)
  785. require.Equal(t, 2, batch.Count())
  786. qresults, err := batch.Send(ctx)
  787. require.NoError(t, err)
  788. require.Len(t, qresults, 2)
  789. require.Equal(t, 0, batch.Count())
  790. qresult1, ok := qresults[0].(*coretypes.ResultABCIQuery)
  791. require.True(t, ok)
  792. require.Equal(t, *qresult1, *q1)
  793. qresult2, ok := qresults[1].(*coretypes.ResultABCIQuery)
  794. require.True(t, ok)
  795. require.Equal(t, *qresult2, *q2)
  796. require.Equal(t, qresult1.Response.Key, k1)
  797. require.Equal(t, qresult2.Response.Key, k2)
  798. require.Equal(t, qresult1.Response.Value, v1)
  799. require.Equal(t, qresult2.Response.Value, v2)
  800. }