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.

661 lines
19 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/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
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
8 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
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
7 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
6 years ago
mempool: move interface into mempool package (#3524) ## Description Refs #2659 Breaking changes in the mempool package: [mempool] #2659 Mempool now an interface old Mempool renamed to CListMempool NewMempool renamed to NewCListMempool Option renamed to CListOption MempoolReactor renamed to Reactor NewMempoolReactor renamed to NewReactor unexpose TxID method TxInfo.PeerID renamed to SenderID unexpose MempoolReactor.Mempool Breaking changes in the state package: [state] #2659 Mempool interface moved to mempool package MockMempool moved to top-level mock package and renamed to Mempool Non Breaking changes in the node package: [node] #2659 Add Mempool method, which allows you to access mempool ## Commits * move Mempool interface into mempool package Refs #2659 Breaking changes in the mempool package: - Mempool now an interface - old Mempool renamed to CListMempool Breaking changes to state package: - MockMempool moved to mempool/mock package and renamed to Mempool - Mempool interface moved to mempool package * assert CListMempool impl Mempool * gofmt code * rename MempoolReactor to Reactor - combine everything into one interface - rename TxInfo.PeerID to TxInfo.SenderID - unexpose MempoolReactor.Mempool * move mempool mock into top-level mock package * add a fixme TxsFront should not be a part of the Mempool interface because it leaks implementation details. Instead, we need to come up with general interface for querying the mempool so the MempoolReactor can fetch and broadcast txs to peers. * change node#Mempool to return interface * save commit = new reactor arch * Revert "save commit = new reactor arch" This reverts commit 1bfceacd9d65a720574683a7f22771e69af9af4d. * require CListMempool in mempool.Reactor * add two changelog entries * fixes after my own review * quote interfaces, structs and functions * fixes after Ismail's review * make node's mempool an interface * make InitWAL/CloseWAL methods a part of Mempool interface * fix merge conflicts * make node's mempool an interface
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
  1. package client_test
  2. import (
  3. "fmt"
  4. "math"
  5. "net/http"
  6. "strings"
  7. "sync"
  8. "testing"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/stretchr/testify/require"
  11. abci "github.com/tendermint/tendermint/abci/types"
  12. "github.com/tendermint/tendermint/libs/log"
  13. tmmath "github.com/tendermint/tendermint/libs/math"
  14. mempl "github.com/tendermint/tendermint/mempool"
  15. "github.com/tendermint/tendermint/rpc/client"
  16. rpchttp "github.com/tendermint/tendermint/rpc/client/http"
  17. rpclocal "github.com/tendermint/tendermint/rpc/client/local"
  18. ctypes "github.com/tendermint/tendermint/rpc/core/types"
  19. rpcclient "github.com/tendermint/tendermint/rpc/jsonrpc/client"
  20. rpctest "github.com/tendermint/tendermint/rpc/test"
  21. "github.com/tendermint/tendermint/types"
  22. )
  23. func getHTTPClient() *rpchttp.HTTP {
  24. rpcAddr := rpctest.GetConfig().RPC.ListenAddress
  25. c, err := rpchttp.New(rpcAddr, "/websocket")
  26. if err != nil {
  27. panic(err)
  28. }
  29. c.SetLogger(log.TestingLogger())
  30. return c
  31. }
  32. func getHTTPClientWithTimeout(timeout uint) *rpchttp.HTTP {
  33. rpcAddr := rpctest.GetConfig().RPC.ListenAddress
  34. c, err := rpchttp.NewWithTimeout(rpcAddr, "/websocket", timeout)
  35. if err != nil {
  36. panic(err)
  37. }
  38. c.SetLogger(log.TestingLogger())
  39. return c
  40. }
  41. func getLocalClient() *rpclocal.Local {
  42. return rpclocal.New(node)
  43. }
  44. // GetClients returns a slice of clients for table-driven tests
  45. func GetClients() []client.Client {
  46. return []client.Client{
  47. getHTTPClient(),
  48. getLocalClient(),
  49. }
  50. }
  51. func TestNilCustomHTTPClient(t *testing.T) {
  52. require.Panics(t, func() {
  53. _, _ = rpchttp.NewWithClient("http://example.com", "/websocket", nil)
  54. })
  55. require.Panics(t, func() {
  56. _, _ = rpcclient.NewWithHTTPClient("http://example.com", nil)
  57. })
  58. }
  59. func TestCustomHTTPClient(t *testing.T) {
  60. remote := rpctest.GetConfig().RPC.ListenAddress
  61. c, err := rpchttp.NewWithClient(remote, "/websocket", http.DefaultClient)
  62. require.Nil(t, err)
  63. status, err := c.Status()
  64. require.NoError(t, err)
  65. require.NotNil(t, status)
  66. }
  67. func TestCorsEnabled(t *testing.T) {
  68. origin := rpctest.GetConfig().RPC.CORSAllowedOrigins[0]
  69. remote := strings.Replace(rpctest.GetConfig().RPC.ListenAddress, "tcp", "http", -1)
  70. req, err := http.NewRequest("GET", remote, nil)
  71. require.Nil(t, err, "%+v", err)
  72. req.Header.Set("Origin", origin)
  73. c := &http.Client{}
  74. resp, err := c.Do(req)
  75. require.Nil(t, err, "%+v", err)
  76. defer resp.Body.Close()
  77. assert.Equal(t, resp.Header.Get("Access-Control-Allow-Origin"), origin)
  78. }
  79. // Make sure status is correct (we connect properly)
  80. func TestStatus(t *testing.T) {
  81. for i, c := range GetClients() {
  82. moniker := rpctest.GetConfig().Moniker
  83. status, err := c.Status()
  84. require.Nil(t, err, "%d: %+v", i, err)
  85. assert.Equal(t, moniker, status.NodeInfo.Moniker)
  86. }
  87. }
  88. // Make sure info is correct (we connect properly)
  89. func TestInfo(t *testing.T) {
  90. for i, c := range GetClients() {
  91. // status, err := c.Status()
  92. // require.Nil(t, err, "%+v", err)
  93. info, err := c.ABCIInfo()
  94. require.Nil(t, err, "%d: %+v", i, err)
  95. // TODO: this is not correct - fix merkleeyes!
  96. // assert.EqualValues(t, status.SyncInfo.LatestBlockHeight, info.Response.LastBlockHeight)
  97. assert.True(t, strings.Contains(info.Response.Data, "size"))
  98. }
  99. }
  100. func TestNetInfo(t *testing.T) {
  101. for i, c := range GetClients() {
  102. nc, ok := c.(client.NetworkClient)
  103. require.True(t, ok, "%d", i)
  104. netinfo, err := nc.NetInfo()
  105. require.Nil(t, err, "%d: %+v", i, err)
  106. assert.True(t, netinfo.Listening)
  107. assert.Equal(t, 0, len(netinfo.Peers))
  108. }
  109. }
  110. func TestDumpConsensusState(t *testing.T) {
  111. for i, c := range GetClients() {
  112. // FIXME: fix server so it doesn't panic on invalid input
  113. nc, ok := c.(client.NetworkClient)
  114. require.True(t, ok, "%d", i)
  115. cons, err := nc.DumpConsensusState()
  116. require.Nil(t, err, "%d: %+v", i, err)
  117. assert.NotEmpty(t, cons.RoundState)
  118. assert.Empty(t, cons.Peers)
  119. }
  120. }
  121. func TestConsensusState(t *testing.T) {
  122. for i, c := range GetClients() {
  123. // FIXME: fix server so it doesn't panic on invalid input
  124. nc, ok := c.(client.NetworkClient)
  125. require.True(t, ok, "%d", i)
  126. cons, err := nc.ConsensusState()
  127. require.Nil(t, err, "%d: %+v", i, err)
  128. assert.NotEmpty(t, cons.RoundState)
  129. }
  130. }
  131. func TestHealth(t *testing.T) {
  132. for i, c := range GetClients() {
  133. nc, ok := c.(client.NetworkClient)
  134. require.True(t, ok, "%d", i)
  135. _, err := nc.Health()
  136. require.Nil(t, err, "%d: %+v", i, err)
  137. }
  138. }
  139. func TestGenesisAndValidators(t *testing.T) {
  140. for i, c := range GetClients() {
  141. // make sure this is the right genesis file
  142. gen, err := c.Genesis()
  143. require.Nil(t, err, "%d: %+v", i, err)
  144. // get the genesis validator
  145. require.Equal(t, 1, len(gen.Genesis.Validators))
  146. gval := gen.Genesis.Validators[0]
  147. // get the current validators
  148. h := int64(1)
  149. vals, err := c.Validators(&h, 0, 0)
  150. require.Nil(t, err, "%d: %+v", i, err)
  151. require.Equal(t, 1, len(vals.Validators))
  152. require.Equal(t, 1, vals.Count)
  153. require.Equal(t, 1, vals.Total)
  154. val := vals.Validators[0]
  155. // make sure the current set is also the genesis set
  156. assert.Equal(t, gval.Power, val.VotingPower)
  157. assert.Equal(t, gval.PubKey, val.PubKey)
  158. }
  159. }
  160. func TestABCIQuery(t *testing.T) {
  161. for i, c := range GetClients() {
  162. // write something
  163. k, v, tx := MakeTxKV()
  164. bres, err := c.BroadcastTxCommit(tx)
  165. require.Nil(t, err, "%d: %+v", i, err)
  166. apph := bres.Height + 1 // this is where the tx will be applied to the state
  167. // wait before querying
  168. client.WaitForHeight(c, apph, nil)
  169. res, err := c.ABCIQuery("/key", k)
  170. qres := res.Response
  171. if assert.Nil(t, err) && assert.True(t, qres.IsOK()) {
  172. assert.EqualValues(t, v, qres.Value)
  173. }
  174. }
  175. }
  176. // Make some app checks
  177. func TestAppCalls(t *testing.T) {
  178. assert, require := assert.New(t), require.New(t)
  179. for i, c := range GetClients() {
  180. // get an offset of height to avoid racing and guessing
  181. s, err := c.Status()
  182. require.Nil(err, "%d: %+v", i, err)
  183. // sh is start height or status height
  184. sh := s.SyncInfo.LatestBlockHeight
  185. // look for the future
  186. h := sh + 2
  187. _, err = c.Block(&h)
  188. assert.NotNil(err) // no block yet
  189. // write something
  190. k, v, tx := MakeTxKV()
  191. bres, err := c.BroadcastTxCommit(tx)
  192. require.Nil(err, "%d: %+v", i, err)
  193. require.True(bres.DeliverTx.IsOK())
  194. txh := bres.Height
  195. apph := txh + 1 // this is where the tx will be applied to the state
  196. // wait before querying
  197. if err := client.WaitForHeight(c, apph, nil); err != nil {
  198. t.Error(err)
  199. }
  200. _qres, err := c.ABCIQueryWithOptions("/key", k, client.ABCIQueryOptions{Prove: false})
  201. qres := _qres.Response
  202. if assert.Nil(err) && assert.True(qres.IsOK()) {
  203. assert.Equal(k, qres.Key)
  204. assert.EqualValues(v, qres.Value)
  205. }
  206. // make sure we can lookup the tx with proof
  207. ptx, err := c.Tx(bres.Hash, true)
  208. require.Nil(err, "%d: %+v", i, err)
  209. assert.EqualValues(txh, ptx.Height)
  210. assert.EqualValues(tx, ptx.Tx)
  211. // and we can even check the block is added
  212. block, err := c.Block(&apph)
  213. require.Nil(err, "%d: %+v", i, err)
  214. appHash := block.Block.Header.AppHash
  215. assert.True(len(appHash) > 0)
  216. assert.EqualValues(apph, block.Block.Header.Height)
  217. // now check the results
  218. blockResults, err := c.BlockResults(&txh)
  219. require.Nil(err, "%d: %+v", i, err)
  220. assert.Equal(txh, blockResults.Height)
  221. if assert.Equal(1, len(blockResults.TxsResults)) {
  222. // check success code
  223. assert.EqualValues(0, blockResults.TxsResults[0].Code)
  224. }
  225. // check blockchain info, now that we know there is info
  226. info, err := c.BlockchainInfo(apph, apph)
  227. require.Nil(err, "%d: %+v", i, err)
  228. assert.True(info.LastHeight >= apph)
  229. if assert.Equal(1, len(info.BlockMetas)) {
  230. lastMeta := info.BlockMetas[0]
  231. assert.EqualValues(apph, lastMeta.Header.Height)
  232. blockData := block.Block
  233. assert.Equal(blockData.Header.AppHash, lastMeta.Header.AppHash)
  234. assert.Equal(block.BlockID, lastMeta.BlockID)
  235. }
  236. // and get the corresponding commit with the same apphash
  237. commit, err := c.Commit(&apph)
  238. require.Nil(err, "%d: %+v", i, err)
  239. cappHash := commit.Header.AppHash
  240. assert.Equal(appHash, cappHash)
  241. assert.NotNil(commit.Commit)
  242. // compare the commits (note Commit(2) has commit from Block(3))
  243. h = apph - 1
  244. commit2, err := c.Commit(&h)
  245. require.Nil(err, "%d: %+v", i, err)
  246. assert.Equal(block.Block.LastCommit, commit2.Commit)
  247. // and we got a proof that works!
  248. _pres, err := c.ABCIQueryWithOptions("/key", k, client.ABCIQueryOptions{Prove: true})
  249. pres := _pres.Response
  250. assert.Nil(err)
  251. assert.True(pres.IsOK())
  252. // XXX Test proof
  253. }
  254. }
  255. func TestBroadcastTxSync(t *testing.T) {
  256. require := require.New(t)
  257. // TODO (melekes): use mempool which is set on RPC rather than getting it from node
  258. mempool := node.Mempool()
  259. initMempoolSize := mempool.Size()
  260. for i, c := range GetClients() {
  261. _, _, tx := MakeTxKV()
  262. bres, err := c.BroadcastTxSync(tx)
  263. require.Nil(err, "%d: %+v", i, err)
  264. require.Equal(bres.Code, abci.CodeTypeOK) // FIXME
  265. require.Equal(initMempoolSize+1, mempool.Size())
  266. txs := mempool.ReapMaxTxs(len(tx))
  267. require.EqualValues(tx, txs[0])
  268. mempool.Flush()
  269. }
  270. }
  271. func TestBroadcastTxCommit(t *testing.T) {
  272. require := require.New(t)
  273. mempool := node.Mempool()
  274. for i, c := range GetClients() {
  275. _, _, tx := MakeTxKV()
  276. bres, err := c.BroadcastTxCommit(tx)
  277. require.Nil(err, "%d: %+v", i, err)
  278. require.True(bres.CheckTx.IsOK())
  279. require.True(bres.DeliverTx.IsOK())
  280. require.Equal(0, mempool.Size())
  281. }
  282. }
  283. func TestUnconfirmedTxs(t *testing.T) {
  284. _, _, tx := MakeTxKV()
  285. mempool := node.Mempool()
  286. _ = mempool.CheckTx(tx, nil, mempl.TxInfo{})
  287. for i, c := range GetClients() {
  288. mc, ok := c.(client.MempoolClient)
  289. require.True(t, ok, "%d", i)
  290. res, err := mc.UnconfirmedTxs(1)
  291. require.Nil(t, err, "%d: %+v", i, err)
  292. assert.Equal(t, 1, res.Count)
  293. assert.Equal(t, 1, res.Total)
  294. assert.Equal(t, mempool.TxsBytes(), res.TotalBytes)
  295. assert.Exactly(t, types.Txs{tx}, types.Txs(res.Txs))
  296. }
  297. mempool.Flush()
  298. }
  299. func TestNumUnconfirmedTxs(t *testing.T) {
  300. _, _, tx := MakeTxKV()
  301. mempool := node.Mempool()
  302. _ = mempool.CheckTx(tx, nil, mempl.TxInfo{})
  303. mempoolSize := mempool.Size()
  304. for i, c := range GetClients() {
  305. mc, ok := c.(client.MempoolClient)
  306. require.True(t, ok, "%d", i)
  307. res, err := mc.NumUnconfirmedTxs()
  308. require.Nil(t, err, "%d: %+v", i, err)
  309. assert.Equal(t, mempoolSize, res.Count)
  310. assert.Equal(t, mempoolSize, res.Total)
  311. assert.Equal(t, mempool.TxsBytes(), res.TotalBytes)
  312. }
  313. mempool.Flush()
  314. }
  315. func TestTx(t *testing.T) {
  316. // first we broadcast a tx
  317. c := getHTTPClient()
  318. _, _, tx := MakeTxKV()
  319. bres, err := c.BroadcastTxCommit(tx)
  320. require.Nil(t, err, "%+v", err)
  321. txHeight := bres.Height
  322. txHash := bres.Hash
  323. anotherTxHash := types.Tx("a different tx").Hash()
  324. cases := []struct {
  325. valid bool
  326. prove bool
  327. hash []byte
  328. }{
  329. // only valid if correct hash provided
  330. {true, false, txHash},
  331. {true, true, txHash},
  332. {false, false, anotherTxHash},
  333. {false, true, anotherTxHash},
  334. {false, false, nil},
  335. {false, true, nil},
  336. }
  337. for i, c := range GetClients() {
  338. for j, tc := range cases {
  339. t.Logf("client %d, case %d", i, j)
  340. // now we query for the tx.
  341. // since there's only one tx, we know index=0.
  342. ptx, err := c.Tx(tc.hash, tc.prove)
  343. if !tc.valid {
  344. require.NotNil(t, err)
  345. } else {
  346. require.Nil(t, err, "%+v", err)
  347. assert.EqualValues(t, txHeight, ptx.Height)
  348. assert.EqualValues(t, tx, ptx.Tx)
  349. assert.Zero(t, ptx.Index)
  350. assert.True(t, ptx.TxResult.IsOK())
  351. assert.EqualValues(t, txHash, ptx.Hash)
  352. // time to verify the proof
  353. proof := ptx.Proof
  354. if tc.prove && assert.EqualValues(t, tx, proof.Data) {
  355. assert.NoError(t, proof.Proof.Verify(proof.RootHash, txHash))
  356. }
  357. }
  358. }
  359. }
  360. }
  361. func TestTxSearchWithTimeout(t *testing.T) {
  362. // Get a client with a time-out of 10 secs.
  363. timeoutClient := getHTTPClientWithTimeout(10)
  364. // query using a compositeKey (see kvstore application)
  365. result, err := timeoutClient.TxSearch("app.creator='Cosmoshi Netowoko'", false, 1, 30, "asc")
  366. require.Nil(t, err)
  367. if len(result.Txs) == 0 {
  368. t.Fatal("expected a lot of transactions")
  369. }
  370. }
  371. func TestTxSearch(t *testing.T) {
  372. c := getHTTPClient()
  373. // first we broadcast a few txs
  374. for i := 0; i < 10; i++ {
  375. _, _, tx := MakeTxKV()
  376. _, err := c.BroadcastTxCommit(tx)
  377. require.NoError(t, err)
  378. }
  379. // since we're not using an isolated test server, we'll have lingering transactions
  380. // from other tests as well
  381. result, err := c.TxSearch("tx.height >= 0", true, 1, 100, "asc")
  382. require.NoError(t, err)
  383. txCount := len(result.Txs)
  384. // pick out the last tx to have something to search for in tests
  385. find := result.Txs[len(result.Txs)-1]
  386. anotherTxHash := types.Tx("a different tx").Hash()
  387. for i, c := range GetClients() {
  388. t.Logf("client %d", i)
  389. // now we query for the tx.
  390. result, err := c.TxSearch(fmt.Sprintf("tx.hash='%v'", find.Hash), true, 1, 30, "asc")
  391. require.Nil(t, err)
  392. require.Len(t, result.Txs, 1)
  393. require.Equal(t, find.Hash, result.Txs[0].Hash)
  394. ptx := result.Txs[0]
  395. assert.EqualValues(t, find.Height, ptx.Height)
  396. assert.EqualValues(t, find.Tx, ptx.Tx)
  397. assert.Zero(t, ptx.Index)
  398. assert.True(t, ptx.TxResult.IsOK())
  399. assert.EqualValues(t, find.Hash, ptx.Hash)
  400. // time to verify the proof
  401. if assert.EqualValues(t, find.Tx, ptx.Proof.Data) {
  402. assert.NoError(t, ptx.Proof.Proof.Verify(ptx.Proof.RootHash, find.Hash))
  403. }
  404. // query by height
  405. result, err = c.TxSearch(fmt.Sprintf("tx.height=%d", find.Height), true, 1, 30, "asc")
  406. require.Nil(t, err)
  407. require.Len(t, result.Txs, 1)
  408. // query for non existing tx
  409. result, err = c.TxSearch(fmt.Sprintf("tx.hash='%X'", anotherTxHash), false, 1, 30, "asc")
  410. require.Nil(t, err)
  411. require.Len(t, result.Txs, 0)
  412. // query using a compositeKey (see kvstore application)
  413. result, err = c.TxSearch("app.creator='Cosmoshi Netowoko'", false, 1, 30, "asc")
  414. require.Nil(t, err)
  415. if len(result.Txs) == 0 {
  416. t.Fatal("expected a lot of transactions")
  417. }
  418. // query using an index key
  419. result, err = c.TxSearch("app.index_key='index is working'", false, 1, 30, "asc")
  420. require.Nil(t, err)
  421. if len(result.Txs) == 0 {
  422. t.Fatal("expected a lot of transactions")
  423. }
  424. // query using an noindex key
  425. result, err = c.TxSearch("app.noindex_key='index is working'", false, 1, 30, "asc")
  426. require.Nil(t, err)
  427. if len(result.Txs) != 0 {
  428. t.Fatal("expected no transaction")
  429. }
  430. // query using a compositeKey (see kvstore application) and height
  431. result, err = c.TxSearch("app.creator='Cosmoshi Netowoko' AND tx.height<10000", true, 1, 30, "asc")
  432. require.Nil(t, err)
  433. if len(result.Txs) == 0 {
  434. t.Fatal("expected a lot of transactions")
  435. }
  436. // query a non existing tx with page 1 and txsPerPage 1
  437. result, err = c.TxSearch("app.creator='Cosmoshi Neetowoko'", true, 1, 1, "asc")
  438. require.Nil(t, err)
  439. require.Len(t, result.Txs, 0)
  440. // check sorting
  441. result, err = c.TxSearch("tx.height >= 1", false, 1, 30, "asc")
  442. require.Nil(t, err)
  443. for k := 0; k < len(result.Txs)-1; k++ {
  444. require.LessOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height)
  445. require.LessOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index)
  446. }
  447. result, err = c.TxSearch("tx.height >= 1", false, 1, 30, "desc")
  448. require.Nil(t, err)
  449. for k := 0; k < len(result.Txs)-1; k++ {
  450. require.GreaterOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height)
  451. require.GreaterOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index)
  452. }
  453. // check pagination
  454. var (
  455. seen = map[int64]bool{}
  456. maxHeight int64
  457. perPage = 3
  458. pages = int(math.Ceil(float64(txCount) / float64(perPage)))
  459. )
  460. for page := 1; page <= pages; page++ {
  461. result, err = c.TxSearch("tx.height >= 1", false, page, perPage, "asc")
  462. require.NoError(t, err)
  463. if page < pages {
  464. require.Len(t, result.Txs, perPage)
  465. } else {
  466. require.LessOrEqual(t, len(result.Txs), perPage)
  467. }
  468. require.Equal(t, txCount, result.TotalCount)
  469. for _, tx := range result.Txs {
  470. require.False(t, seen[tx.Height],
  471. "Found duplicate height %v in page %v", tx.Height, page)
  472. require.Greater(t, tx.Height, maxHeight,
  473. "Found decreasing height %v (max seen %v) in page %v", tx.Height, maxHeight, page)
  474. seen[tx.Height] = true
  475. maxHeight = tx.Height
  476. }
  477. }
  478. require.Len(t, seen, txCount)
  479. }
  480. }
  481. func TestBatchedJSONRPCCalls(t *testing.T) {
  482. c := getHTTPClient()
  483. testBatchedJSONRPCCalls(t, c)
  484. }
  485. func testBatchedJSONRPCCalls(t *testing.T, c *rpchttp.HTTP) {
  486. k1, v1, tx1 := MakeTxKV()
  487. k2, v2, tx2 := MakeTxKV()
  488. batch := c.NewBatch()
  489. r1, err := batch.BroadcastTxCommit(tx1)
  490. require.NoError(t, err)
  491. r2, err := batch.BroadcastTxCommit(tx2)
  492. require.NoError(t, err)
  493. require.Equal(t, 2, batch.Count())
  494. bresults, err := batch.Send()
  495. require.NoError(t, err)
  496. require.Len(t, bresults, 2)
  497. require.Equal(t, 0, batch.Count())
  498. bresult1, ok := bresults[0].(*ctypes.ResultBroadcastTxCommit)
  499. require.True(t, ok)
  500. require.Equal(t, *bresult1, *r1)
  501. bresult2, ok := bresults[1].(*ctypes.ResultBroadcastTxCommit)
  502. require.True(t, ok)
  503. require.Equal(t, *bresult2, *r2)
  504. apph := tmmath.MaxInt64(bresult1.Height, bresult2.Height) + 1
  505. client.WaitForHeight(c, apph, nil)
  506. q1, err := batch.ABCIQuery("/key", k1)
  507. require.NoError(t, err)
  508. q2, err := batch.ABCIQuery("/key", k2)
  509. require.NoError(t, err)
  510. require.Equal(t, 2, batch.Count())
  511. qresults, err := batch.Send()
  512. require.NoError(t, err)
  513. require.Len(t, qresults, 2)
  514. require.Equal(t, 0, batch.Count())
  515. qresult1, ok := qresults[0].(*ctypes.ResultABCIQuery)
  516. require.True(t, ok)
  517. require.Equal(t, *qresult1, *q1)
  518. qresult2, ok := qresults[1].(*ctypes.ResultABCIQuery)
  519. require.True(t, ok)
  520. require.Equal(t, *qresult2, *q2)
  521. require.Equal(t, qresult1.Response.Key, k1)
  522. require.Equal(t, qresult2.Response.Key, k2)
  523. require.Equal(t, qresult1.Response.Value, v1)
  524. require.Equal(t, qresult2.Response.Value, v2)
  525. }
  526. func TestBatchedJSONRPCCallsCancellation(t *testing.T) {
  527. c := getHTTPClient()
  528. _, _, tx1 := MakeTxKV()
  529. _, _, tx2 := MakeTxKV()
  530. batch := c.NewBatch()
  531. _, err := batch.BroadcastTxCommit(tx1)
  532. require.NoError(t, err)
  533. _, err = batch.BroadcastTxCommit(tx2)
  534. require.NoError(t, err)
  535. // we should have 2 requests waiting
  536. require.Equal(t, 2, batch.Count())
  537. // we want to make sure we cleared 2 pending requests
  538. require.Equal(t, 2, batch.Clear())
  539. // now there should be no batched requests
  540. require.Equal(t, 0, batch.Count())
  541. }
  542. func TestSendingEmptyRequestBatch(t *testing.T) {
  543. c := getHTTPClient()
  544. batch := c.NewBatch()
  545. _, err := batch.Send()
  546. require.Error(t, err, "sending an empty batch of JSON RPC requests should result in an error")
  547. }
  548. func TestClearingEmptyRequestBatch(t *testing.T) {
  549. c := getHTTPClient()
  550. batch := c.NewBatch()
  551. require.Zero(t, batch.Clear(), "clearing an empty batch of JSON RPC requests should result in a 0 result")
  552. }
  553. func TestConcurrentJSONRPCBatching(t *testing.T) {
  554. var wg sync.WaitGroup
  555. c := getHTTPClient()
  556. for i := 0; i < 50; i++ {
  557. wg.Add(1)
  558. go func() {
  559. defer wg.Done()
  560. testBatchedJSONRPCCalls(t, c)
  561. }()
  562. }
  563. wg.Wait()
  564. }