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.

796 lines
23 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
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
5 years ago
lint: Enable Golint (#4212) * Fix many golint errors * Fix golint errors in the 'lite' package * Don't export Pool.store * Fix typo * Revert unwanted changes * Fix errors in counter package * Fix linter errors in kvstore package * Fix linter error in example package * Fix error in tests package * Fix linter errors in v2 package * Fix linter errors in consensus package * Fix linter errors in evidence package * Fix linter error in fail package * Fix linter errors in query package * Fix linter errors in core package * Fix linter errors in node package * Fix linter errors in mempool package * Fix linter error in conn package * Fix linter errors in pex package * Rename PEXReactor export to Reactor * Fix linter errors in trust package * Fix linter errors in upnp package * Fix linter errors in p2p package * Fix linter errors in proxy package * Fix linter errors in mock_test package * Fix linter error in client_test package * Fix linter errors in coretypes package * Fix linter errors in coregrpc package * Fix linter errors in rpcserver package * Fix linter errors in rpctypes package * Fix linter errors in rpctest package * Fix linter error in json2wal script * Fix linter error in wal2json script * Fix linter errors in kv package * Fix linter error in state package * Fix linter error in grpc_client * Fix linter errors in types package * Fix linter error in version package * Fix remaining errors * Address review comments * Fix broken tests * Reconcile package coregrpc * Fix golangci bot error * Fix new golint errors * Fix broken reference * Enable golint linter * minor changes to bring golint into line * fix failing test * fix pex reactor naming * address PR comments
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
  1. package client_test
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math"
  6. "math/rand"
  7. "net/http"
  8. "strings"
  9. "sync"
  10. "testing"
  11. "time"
  12. "github.com/stretchr/testify/assert"
  13. "github.com/stretchr/testify/require"
  14. abci "github.com/tendermint/tendermint/abci/types"
  15. "github.com/tendermint/tendermint/crypto/ed25519"
  16. "github.com/tendermint/tendermint/crypto/tmhash"
  17. "github.com/tendermint/tendermint/libs/log"
  18. tmmath "github.com/tendermint/tendermint/libs/math"
  19. mempl "github.com/tendermint/tendermint/mempool"
  20. "github.com/tendermint/tendermint/privval"
  21. "github.com/tendermint/tendermint/rpc/client"
  22. rpchttp "github.com/tendermint/tendermint/rpc/client/http"
  23. rpclocal "github.com/tendermint/tendermint/rpc/client/local"
  24. ctypes "github.com/tendermint/tendermint/rpc/core/types"
  25. rpcclient "github.com/tendermint/tendermint/rpc/lib/client"
  26. rpctest "github.com/tendermint/tendermint/rpc/test"
  27. "github.com/tendermint/tendermint/types"
  28. )
  29. func getHTTPClient() *rpchttp.HTTP {
  30. rpcAddr := rpctest.GetConfig().RPC.ListenAddress
  31. c, err := rpchttp.New(rpcAddr, "/websocket")
  32. if err != nil {
  33. panic(err)
  34. }
  35. c.SetLogger(log.TestingLogger())
  36. return c
  37. }
  38. func getHTTPClientWithTimeout(timeout uint) *rpchttp.HTTP {
  39. rpcAddr := rpctest.GetConfig().RPC.ListenAddress
  40. c, err := rpchttp.NewWithTimeout(rpcAddr, "/websocket", timeout)
  41. if err != nil {
  42. panic(err)
  43. }
  44. c.SetLogger(log.TestingLogger())
  45. return c
  46. }
  47. func getLocalClient() *rpclocal.Local {
  48. return rpclocal.New(node)
  49. }
  50. // GetClients returns a slice of clients for table-driven tests
  51. func GetClients() []client.Client {
  52. return []client.Client{
  53. getHTTPClient(),
  54. getLocalClient(),
  55. }
  56. }
  57. func TestNilCustomHTTPClient(t *testing.T) {
  58. require.Panics(t, func() {
  59. _, _ = rpchttp.NewWithClient("http://example.com", "/websocket", nil)
  60. })
  61. require.Panics(t, func() {
  62. _, _ = rpcclient.NewJSONRPCClientWithHTTPClient("http://example.com", nil)
  63. })
  64. }
  65. func TestCustomHTTPClient(t *testing.T) {
  66. remote := rpctest.GetConfig().RPC.ListenAddress
  67. c, err := rpchttp.NewWithClient(remote, "/websocket", http.DefaultClient)
  68. require.Nil(t, err)
  69. status, err := c.Status()
  70. require.NoError(t, err)
  71. require.NotNil(t, status)
  72. }
  73. func TestCorsEnabled(t *testing.T) {
  74. origin := rpctest.GetConfig().RPC.CORSAllowedOrigins[0]
  75. remote := strings.Replace(rpctest.GetConfig().RPC.ListenAddress, "tcp", "http", -1)
  76. req, err := http.NewRequest("GET", remote, nil)
  77. require.Nil(t, err, "%+v", err)
  78. req.Header.Set("Origin", origin)
  79. c := &http.Client{}
  80. resp, err := c.Do(req)
  81. require.Nil(t, err, "%+v", err)
  82. defer resp.Body.Close()
  83. assert.Equal(t, resp.Header.Get("Access-Control-Allow-Origin"), origin)
  84. }
  85. // Make sure status is correct (we connect properly)
  86. func TestStatus(t *testing.T) {
  87. for i, c := range GetClients() {
  88. moniker := rpctest.GetConfig().Moniker
  89. status, err := c.Status()
  90. require.Nil(t, err, "%d: %+v", i, err)
  91. assert.Equal(t, moniker, status.NodeInfo.Moniker)
  92. }
  93. }
  94. // Make sure info is correct (we connect properly)
  95. func TestInfo(t *testing.T) {
  96. for i, c := range GetClients() {
  97. // status, err := c.Status()
  98. // require.Nil(t, err, "%+v", err)
  99. info, err := c.ABCIInfo()
  100. require.Nil(t, err, "%d: %+v", i, err)
  101. // TODO: this is not correct - fix merkleeyes!
  102. // assert.EqualValues(t, status.SyncInfo.LatestBlockHeight, info.Response.LastBlockHeight)
  103. assert.True(t, strings.Contains(info.Response.Data, "size"))
  104. }
  105. }
  106. func TestNetInfo(t *testing.T) {
  107. for i, c := range GetClients() {
  108. nc, ok := c.(client.NetworkClient)
  109. require.True(t, ok, "%d", i)
  110. netinfo, err := nc.NetInfo()
  111. require.Nil(t, err, "%d: %+v", i, err)
  112. assert.True(t, netinfo.Listening)
  113. assert.Equal(t, 0, len(netinfo.Peers))
  114. }
  115. }
  116. func TestDumpConsensusState(t *testing.T) {
  117. for i, c := range GetClients() {
  118. // FIXME: fix server so it doesn't panic on invalid input
  119. nc, ok := c.(client.NetworkClient)
  120. require.True(t, ok, "%d", i)
  121. cons, err := nc.DumpConsensusState()
  122. require.Nil(t, err, "%d: %+v", i, err)
  123. assert.NotEmpty(t, cons.RoundState)
  124. assert.Empty(t, cons.Peers)
  125. }
  126. }
  127. func TestConsensusState(t *testing.T) {
  128. for i, c := range GetClients() {
  129. // FIXME: fix server so it doesn't panic on invalid input
  130. nc, ok := c.(client.NetworkClient)
  131. require.True(t, ok, "%d", i)
  132. cons, err := nc.ConsensusState()
  133. require.Nil(t, err, "%d: %+v", i, err)
  134. assert.NotEmpty(t, cons.RoundState)
  135. }
  136. }
  137. func TestHealth(t *testing.T) {
  138. for i, c := range GetClients() {
  139. nc, ok := c.(client.NetworkClient)
  140. require.True(t, ok, "%d", i)
  141. _, err := nc.Health()
  142. require.Nil(t, err, "%d: %+v", i, err)
  143. }
  144. }
  145. func TestGenesisAndValidators(t *testing.T) {
  146. for i, c := range GetClients() {
  147. // make sure this is the right genesis file
  148. gen, err := c.Genesis()
  149. require.Nil(t, err, "%d: %+v", i, err)
  150. // get the genesis validator
  151. require.Equal(t, 1, len(gen.Genesis.Validators))
  152. gval := gen.Genesis.Validators[0]
  153. // get the current validators
  154. vals, err := c.Validators(nil, 0, 0)
  155. require.Nil(t, err, "%d: %+v", i, err)
  156. require.Equal(t, 1, len(vals.Validators))
  157. val := vals.Validators[0]
  158. // make sure the current set is also the genesis set
  159. assert.Equal(t, gval.Power, val.VotingPower)
  160. assert.Equal(t, gval.PubKey, val.PubKey)
  161. }
  162. }
  163. func TestABCIQuery(t *testing.T) {
  164. for i, c := range GetClients() {
  165. // write something
  166. k, v, tx := MakeTxKV()
  167. bres, err := c.BroadcastTxCommit(tx)
  168. require.Nil(t, err, "%d: %+v", i, err)
  169. apph := bres.Height + 1 // this is where the tx will be applied to the state
  170. // wait before querying
  171. client.WaitForHeight(c, apph, nil)
  172. res, err := c.ABCIQuery("/key", k)
  173. qres := res.Response
  174. if assert.Nil(t, err) && assert.True(t, qres.IsOK()) {
  175. assert.EqualValues(t, v, qres.Value)
  176. }
  177. }
  178. }
  179. // Make some app checks
  180. func TestAppCalls(t *testing.T) {
  181. assert, require := assert.New(t), require.New(t)
  182. for i, c := range GetClients() {
  183. // get an offset of height to avoid racing and guessing
  184. s, err := c.Status()
  185. require.Nil(err, "%d: %+v", i, err)
  186. // sh is start height or status height
  187. sh := s.SyncInfo.LatestBlockHeight
  188. // look for the future
  189. h := sh + 2
  190. _, err = c.Block(&h)
  191. assert.NotNil(err) // no block yet
  192. // write something
  193. k, v, tx := MakeTxKV()
  194. bres, err := c.BroadcastTxCommit(tx)
  195. require.Nil(err, "%d: %+v", i, err)
  196. require.True(bres.DeliverTx.IsOK())
  197. txh := bres.Height
  198. apph := txh + 1 // this is where the tx will be applied to the state
  199. // wait before querying
  200. if err := client.WaitForHeight(c, apph, nil); err != nil {
  201. t.Error(err)
  202. }
  203. _qres, err := c.ABCIQueryWithOptions("/key", k, client.ABCIQueryOptions{Prove: false})
  204. qres := _qres.Response
  205. if assert.Nil(err) && assert.True(qres.IsOK()) {
  206. assert.Equal(k, qres.Key)
  207. assert.EqualValues(v, qres.Value)
  208. }
  209. // make sure we can lookup the tx with proof
  210. ptx, err := c.Tx(bres.Hash, true)
  211. require.Nil(err, "%d: %+v", i, err)
  212. assert.EqualValues(txh, ptx.Height)
  213. assert.EqualValues(tx, ptx.Tx)
  214. // and we can even check the block is added
  215. block, err := c.Block(&apph)
  216. require.Nil(err, "%d: %+v", i, err)
  217. appHash := block.Block.Header.AppHash
  218. assert.True(len(appHash) > 0)
  219. assert.EqualValues(apph, block.Block.Header.Height)
  220. // now check the results
  221. blockResults, err := c.BlockResults(&txh)
  222. require.Nil(err, "%d: %+v", i, err)
  223. assert.Equal(txh, blockResults.Height)
  224. if assert.Equal(1, len(blockResults.TxsResults)) {
  225. // check success code
  226. assert.EqualValues(0, blockResults.TxsResults[0].Code)
  227. }
  228. // check blockchain info, now that we know there is info
  229. info, err := c.BlockchainInfo(apph, apph)
  230. require.Nil(err, "%d: %+v", i, err)
  231. assert.True(info.LastHeight >= apph)
  232. if assert.Equal(1, len(info.BlockMetas)) {
  233. lastMeta := info.BlockMetas[0]
  234. assert.EqualValues(apph, lastMeta.Header.Height)
  235. blockData := block.Block
  236. assert.Equal(blockData.Header.AppHash, lastMeta.Header.AppHash)
  237. assert.Equal(block.BlockID, lastMeta.BlockID)
  238. }
  239. // and get the corresponding commit with the same apphash
  240. commit, err := c.Commit(&apph)
  241. require.Nil(err, "%d: %+v", i, err)
  242. cappHash := commit.Header.AppHash
  243. assert.Equal(appHash, cappHash)
  244. assert.NotNil(commit.Commit)
  245. // compare the commits (note Commit(2) has commit from Block(3))
  246. h = apph - 1
  247. commit2, err := c.Commit(&h)
  248. require.Nil(err, "%d: %+v", i, err)
  249. assert.Equal(block.Block.LastCommit, commit2.Commit)
  250. // and we got a proof that works!
  251. _pres, err := c.ABCIQueryWithOptions("/key", k, client.ABCIQueryOptions{Prove: true})
  252. pres := _pres.Response
  253. assert.Nil(err)
  254. assert.True(pres.IsOK())
  255. // XXX Test proof
  256. }
  257. }
  258. func TestBroadcastTxSync(t *testing.T) {
  259. require := require.New(t)
  260. // TODO (melekes): use mempool which is set on RPC rather than getting it from node
  261. mempool := node.Mempool()
  262. initMempoolSize := mempool.Size()
  263. for i, c := range GetClients() {
  264. _, _, tx := MakeTxKV()
  265. bres, err := c.BroadcastTxSync(tx)
  266. require.Nil(err, "%d: %+v", i, err)
  267. require.Equal(bres.Code, abci.CodeTypeOK) // FIXME
  268. require.Equal(initMempoolSize+1, mempool.Size())
  269. txs := mempool.ReapMaxTxs(len(tx))
  270. require.EqualValues(tx, txs[0])
  271. mempool.Flush()
  272. }
  273. }
  274. func TestBroadcastTxCommit(t *testing.T) {
  275. require := require.New(t)
  276. mempool := node.Mempool()
  277. for i, c := range GetClients() {
  278. _, _, tx := MakeTxKV()
  279. bres, err := c.BroadcastTxCommit(tx)
  280. require.Nil(err, "%d: %+v", i, err)
  281. require.True(bres.CheckTx.IsOK())
  282. require.True(bres.DeliverTx.IsOK())
  283. require.Equal(0, mempool.Size())
  284. }
  285. }
  286. func TestUnconfirmedTxs(t *testing.T) {
  287. _, _, tx := MakeTxKV()
  288. mempool := node.Mempool()
  289. _ = mempool.CheckTx(tx, nil, mempl.TxInfo{})
  290. for i, c := range GetClients() {
  291. mc, ok := c.(client.MempoolClient)
  292. require.True(t, ok, "%d", i)
  293. res, err := mc.UnconfirmedTxs(1)
  294. require.Nil(t, err, "%d: %+v", i, err)
  295. assert.Equal(t, 1, res.Count)
  296. assert.Equal(t, 1, res.Total)
  297. assert.Equal(t, mempool.TxsBytes(), res.TotalBytes)
  298. assert.Exactly(t, types.Txs{tx}, types.Txs(res.Txs))
  299. }
  300. mempool.Flush()
  301. }
  302. func TestNumUnconfirmedTxs(t *testing.T) {
  303. _, _, tx := MakeTxKV()
  304. mempool := node.Mempool()
  305. _ = mempool.CheckTx(tx, nil, mempl.TxInfo{})
  306. mempoolSize := mempool.Size()
  307. for i, c := range GetClients() {
  308. mc, ok := c.(client.MempoolClient)
  309. require.True(t, ok, "%d", i)
  310. res, err := mc.NumUnconfirmedTxs()
  311. require.Nil(t, err, "%d: %+v", i, err)
  312. assert.Equal(t, mempoolSize, res.Count)
  313. assert.Equal(t, mempoolSize, res.Total)
  314. assert.Equal(t, mempool.TxsBytes(), res.TotalBytes)
  315. }
  316. mempool.Flush()
  317. }
  318. func TestTx(t *testing.T) {
  319. // first we broadcast a tx
  320. c := getHTTPClient()
  321. _, _, tx := MakeTxKV()
  322. bres, err := c.BroadcastTxCommit(tx)
  323. require.Nil(t, err, "%+v", err)
  324. txHeight := bres.Height
  325. txHash := bres.Hash
  326. anotherTxHash := types.Tx("a different tx").Hash()
  327. cases := []struct {
  328. valid bool
  329. prove bool
  330. hash []byte
  331. }{
  332. // only valid if correct hash provided
  333. {true, false, txHash},
  334. {true, true, txHash},
  335. {false, false, anotherTxHash},
  336. {false, true, anotherTxHash},
  337. {false, false, nil},
  338. {false, true, nil},
  339. }
  340. for i, c := range GetClients() {
  341. for j, tc := range cases {
  342. t.Logf("client %d, case %d", i, j)
  343. // now we query for the tx.
  344. // since there's only one tx, we know index=0.
  345. ptx, err := c.Tx(tc.hash, tc.prove)
  346. if !tc.valid {
  347. require.NotNil(t, err)
  348. } else {
  349. require.Nil(t, err, "%+v", err)
  350. assert.EqualValues(t, txHeight, ptx.Height)
  351. assert.EqualValues(t, tx, ptx.Tx)
  352. assert.Zero(t, ptx.Index)
  353. assert.True(t, ptx.TxResult.IsOK())
  354. assert.EqualValues(t, txHash, ptx.Hash)
  355. // time to verify the proof
  356. proof := ptx.Proof
  357. if tc.prove && assert.EqualValues(t, tx, proof.Data) {
  358. assert.NoError(t, proof.Proof.Verify(proof.RootHash, txHash))
  359. }
  360. }
  361. }
  362. }
  363. }
  364. func TestTxSearchWithTimeout(t *testing.T) {
  365. // Get a client with a time-out of 10 secs.
  366. timeoutClient := getHTTPClientWithTimeout(10)
  367. // query using a compositeKey (see kvstore application)
  368. result, err := timeoutClient.TxSearch("app.creator='Cosmoshi Netowoko'", false, 1, 30, "asc")
  369. require.Nil(t, err)
  370. if len(result.Txs) == 0 {
  371. t.Fatal("expected a lot of transactions")
  372. }
  373. }
  374. func TestTxSearch(t *testing.T) {
  375. c := getHTTPClient()
  376. // first we broadcast a few txs
  377. for i := 0; i < 10; i++ {
  378. _, _, tx := MakeTxKV()
  379. _, err := c.BroadcastTxCommit(tx)
  380. require.NoError(t, err)
  381. }
  382. // since we're not using an isolated test server, we'll have lingering transactions
  383. // from other tests as well
  384. result, err := c.TxSearch("tx.height >= 0", true, 1, 100, "asc")
  385. require.NoError(t, err)
  386. txCount := len(result.Txs)
  387. // pick out the last tx to have something to search for in tests
  388. find := result.Txs[len(result.Txs)-1]
  389. anotherTxHash := types.Tx("a different tx").Hash()
  390. for i, c := range GetClients() {
  391. t.Logf("client %d", i)
  392. // now we query for the tx.
  393. result, err := c.TxSearch(fmt.Sprintf("tx.hash='%v'", find.Hash), true, 1, 30, "asc")
  394. require.Nil(t, err)
  395. require.Len(t, result.Txs, 1)
  396. require.Equal(t, find.Hash, result.Txs[0].Hash)
  397. ptx := result.Txs[0]
  398. assert.EqualValues(t, find.Height, ptx.Height)
  399. assert.EqualValues(t, find.Tx, ptx.Tx)
  400. assert.Zero(t, ptx.Index)
  401. assert.True(t, ptx.TxResult.IsOK())
  402. assert.EqualValues(t, find.Hash, ptx.Hash)
  403. // time to verify the proof
  404. if assert.EqualValues(t, find.Tx, ptx.Proof.Data) {
  405. assert.NoError(t, ptx.Proof.Proof.Verify(ptx.Proof.RootHash, find.Hash))
  406. }
  407. // query by height
  408. result, err = c.TxSearch(fmt.Sprintf("tx.height=%d", find.Height), true, 1, 30, "asc")
  409. require.Nil(t, err)
  410. require.Len(t, result.Txs, 1)
  411. // query for non existing tx
  412. result, err = c.TxSearch(fmt.Sprintf("tx.hash='%X'", anotherTxHash), false, 1, 30, "asc")
  413. require.Nil(t, err)
  414. require.Len(t, result.Txs, 0)
  415. // query using a compositeKey (see kvstore application)
  416. result, err = c.TxSearch("app.creator='Cosmoshi Netowoko'", false, 1, 30, "asc")
  417. require.Nil(t, err)
  418. if len(result.Txs) == 0 {
  419. t.Fatal("expected a lot of transactions")
  420. }
  421. // query using a compositeKey (see kvstore application) and height
  422. result, err = c.TxSearch("app.creator='Cosmoshi Netowoko' AND tx.height<10000", true, 1, 30, "asc")
  423. require.Nil(t, err)
  424. if len(result.Txs) == 0 {
  425. t.Fatal("expected a lot of transactions")
  426. }
  427. // query a non existing tx with page 1 and txsPerPage 1
  428. result, err = c.TxSearch("app.creator='Cosmoshi Neetowoko'", true, 1, 1, "asc")
  429. require.Nil(t, err)
  430. require.Len(t, result.Txs, 0)
  431. // check sorting
  432. result, err = c.TxSearch(fmt.Sprintf("tx.height >= 1"), false, 1, 30, "asc")
  433. require.Nil(t, err)
  434. for k := 0; k < len(result.Txs)-1; k++ {
  435. require.LessOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height)
  436. require.LessOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index)
  437. }
  438. result, err = c.TxSearch(fmt.Sprintf("tx.height >= 1"), false, 1, 30, "desc")
  439. require.Nil(t, err)
  440. for k := 0; k < len(result.Txs)-1; k++ {
  441. require.GreaterOrEqual(t, result.Txs[k].Height, result.Txs[k+1].Height)
  442. require.GreaterOrEqual(t, result.Txs[k].Index, result.Txs[k+1].Index)
  443. }
  444. // check pagination
  445. var (
  446. seen = map[int64]bool{}
  447. maxHeight int64
  448. perPage = 3
  449. pages = int(math.Ceil(float64(txCount) / float64(perPage)))
  450. )
  451. for page := 1; page <= pages; page++ {
  452. result, err = c.TxSearch("tx.height >= 1", false, page, perPage, "asc")
  453. require.NoError(t, err)
  454. if page < pages {
  455. require.Len(t, result.Txs, perPage)
  456. } else {
  457. require.LessOrEqual(t, len(result.Txs), perPage)
  458. }
  459. require.Equal(t, txCount, result.TotalCount)
  460. for _, tx := range result.Txs {
  461. require.False(t, seen[tx.Height],
  462. "Found duplicate height %v in page %v", tx.Height, page)
  463. require.Greater(t, tx.Height, maxHeight,
  464. "Found decreasing height %v (max seen %v) in page %v", tx.Height, maxHeight, page)
  465. seen[tx.Height] = true
  466. maxHeight = tx.Height
  467. }
  468. }
  469. require.Len(t, seen, txCount)
  470. }
  471. }
  472. func deepcpVote(vote *types.Vote) (res *types.Vote) {
  473. res = &types.Vote{
  474. ValidatorAddress: make([]byte, len(vote.ValidatorAddress)),
  475. ValidatorIndex: vote.ValidatorIndex,
  476. Height: vote.Height,
  477. Round: vote.Round,
  478. Type: vote.Type,
  479. Timestamp: vote.Timestamp,
  480. BlockID: types.BlockID{
  481. Hash: make([]byte, len(vote.BlockID.Hash)),
  482. PartsHeader: vote.BlockID.PartsHeader,
  483. },
  484. Signature: make([]byte, len(vote.Signature)),
  485. }
  486. copy(res.ValidatorAddress, vote.ValidatorAddress)
  487. copy(res.BlockID.Hash, vote.BlockID.Hash)
  488. copy(res.Signature, vote.Signature)
  489. return
  490. }
  491. func newEvidence(
  492. t *testing.T,
  493. val *privval.FilePV,
  494. vote *types.Vote,
  495. vote2 *types.Vote,
  496. chainID string,
  497. ) types.DuplicateVoteEvidence {
  498. var err error
  499. deepcpVote2 := deepcpVote(vote2)
  500. deepcpVote2.Signature, err = val.Key.PrivKey.Sign(deepcpVote2.SignBytes(chainID))
  501. require.NoError(t, err)
  502. return *types.NewDuplicateVoteEvidence(val.Key.PubKey, vote, deepcpVote2)
  503. }
  504. func makeEvidences(
  505. t *testing.T,
  506. val *privval.FilePV,
  507. chainID string,
  508. ) (ev types.DuplicateVoteEvidence, fakes []types.DuplicateVoteEvidence) {
  509. vote := &types.Vote{
  510. ValidatorAddress: val.Key.Address,
  511. ValidatorIndex: 0,
  512. Height: 1,
  513. Round: 0,
  514. Type: types.PrevoteType,
  515. Timestamp: time.Now().UTC(),
  516. BlockID: types.BlockID{
  517. Hash: tmhash.Sum([]byte("blockhash")),
  518. PartsHeader: types.PartSetHeader{
  519. Total: 1000,
  520. Hash: tmhash.Sum([]byte("partset")),
  521. },
  522. },
  523. }
  524. var err error
  525. vote.Signature, err = val.Key.PrivKey.Sign(vote.SignBytes(chainID))
  526. require.NoError(t, err)
  527. vote2 := deepcpVote(vote)
  528. vote2.BlockID.Hash = tmhash.Sum([]byte("blockhash2"))
  529. ev = newEvidence(t, val, vote, vote2, chainID)
  530. fakes = make([]types.DuplicateVoteEvidence, 42)
  531. // different address
  532. vote2 = deepcpVote(vote)
  533. for i := 0; i < 10; i++ {
  534. rand.Read(vote2.ValidatorAddress) // nolint: gosec
  535. fakes[i] = newEvidence(t, val, vote, vote2, chainID)
  536. }
  537. // different index
  538. vote2 = deepcpVote(vote)
  539. for i := 10; i < 20; i++ {
  540. vote2.ValidatorIndex = rand.Int()%100 + 1 // nolint: gosec
  541. fakes[i] = newEvidence(t, val, vote, vote2, chainID)
  542. }
  543. // different height
  544. vote2 = deepcpVote(vote)
  545. for i := 20; i < 30; i++ {
  546. vote2.Height = rand.Int63()%1000 + 100 // nolint: gosec
  547. fakes[i] = newEvidence(t, val, vote, vote2, chainID)
  548. }
  549. // different round
  550. vote2 = deepcpVote(vote)
  551. for i := 30; i < 40; i++ {
  552. vote2.Round = rand.Int()%10 + 1 // nolint: gosec
  553. fakes[i] = newEvidence(t, val, vote, vote2, chainID)
  554. }
  555. // different type
  556. vote2 = deepcpVote(vote)
  557. vote2.Type = types.PrecommitType
  558. fakes[40] = newEvidence(t, val, vote, vote2, chainID)
  559. // exactly same vote
  560. vote2 = deepcpVote(vote)
  561. fakes[41] = newEvidence(t, val, vote, vote2, chainID)
  562. return ev, fakes
  563. }
  564. func TestBroadcastEvidenceDuplicateVote(t *testing.T) {
  565. config := rpctest.GetConfig()
  566. chainID := config.ChainID()
  567. pvKeyFile := config.PrivValidatorKeyFile()
  568. pvKeyStateFile := config.PrivValidatorStateFile()
  569. pv := privval.LoadOrGenFilePV(pvKeyFile, pvKeyStateFile)
  570. ev, fakes := makeEvidences(t, pv, chainID)
  571. t.Logf("evidence %v", ev)
  572. for i, c := range GetClients() {
  573. t.Logf("client %d", i)
  574. result, err := c.BroadcastEvidence(&ev)
  575. require.Nil(t, err)
  576. require.Equal(t, ev.Hash(), result.Hash, "Invalid response, result %+v", result)
  577. status, err := c.Status()
  578. require.NoError(t, err)
  579. client.WaitForHeight(c, status.SyncInfo.LatestBlockHeight+2, nil)
  580. ed25519pub := ev.PubKey.(ed25519.PubKeyEd25519)
  581. rawpub := ed25519pub[:]
  582. result2, err := c.ABCIQuery("/val", rawpub)
  583. require.Nil(t, err, "Error querying evidence, err %v", err)
  584. qres := result2.Response
  585. require.True(t, qres.IsOK(), "Response not OK")
  586. var v abci.ValidatorUpdate
  587. err = abci.ReadMessage(bytes.NewReader(qres.Value), &v)
  588. require.NoError(t, err, "Error reading query result, value %v", qres.Value)
  589. require.EqualValues(t, rawpub, v.PubKey.Data, "Stored PubKey not equal with expected, value %v", string(qres.Value))
  590. require.Equal(t, int64(9), v.Power, "Stored Power not equal with expected, value %v", string(qres.Value))
  591. for _, fake := range fakes {
  592. _, err := c.BroadcastEvidence(&types.DuplicateVoteEvidence{
  593. PubKey: fake.PubKey,
  594. VoteA: fake.VoteA,
  595. VoteB: fake.VoteB})
  596. require.Error(t, err, "Broadcasting fake evidence succeed: %s", fake.String())
  597. }
  598. }
  599. }
  600. func TestBatchedJSONRPCCalls(t *testing.T) {
  601. c := getHTTPClient()
  602. testBatchedJSONRPCCalls(t, c)
  603. }
  604. func testBatchedJSONRPCCalls(t *testing.T, c *rpchttp.HTTP) {
  605. k1, v1, tx1 := MakeTxKV()
  606. k2, v2, tx2 := MakeTxKV()
  607. batch := c.NewBatch()
  608. r1, err := batch.BroadcastTxCommit(tx1)
  609. require.NoError(t, err)
  610. r2, err := batch.BroadcastTxCommit(tx2)
  611. require.NoError(t, err)
  612. require.Equal(t, 2, batch.Count())
  613. bresults, err := batch.Send()
  614. require.NoError(t, err)
  615. require.Len(t, bresults, 2)
  616. require.Equal(t, 0, batch.Count())
  617. bresult1, ok := bresults[0].(*ctypes.ResultBroadcastTxCommit)
  618. require.True(t, ok)
  619. require.Equal(t, *bresult1, *r1)
  620. bresult2, ok := bresults[1].(*ctypes.ResultBroadcastTxCommit)
  621. require.True(t, ok)
  622. require.Equal(t, *bresult2, *r2)
  623. apph := tmmath.MaxInt64(bresult1.Height, bresult2.Height) + 1
  624. client.WaitForHeight(c, apph, nil)
  625. q1, err := batch.ABCIQuery("/key", k1)
  626. require.NoError(t, err)
  627. q2, err := batch.ABCIQuery("/key", k2)
  628. require.NoError(t, err)
  629. require.Equal(t, 2, batch.Count())
  630. qresults, err := batch.Send()
  631. require.NoError(t, err)
  632. require.Len(t, qresults, 2)
  633. require.Equal(t, 0, batch.Count())
  634. qresult1, ok := qresults[0].(*ctypes.ResultABCIQuery)
  635. require.True(t, ok)
  636. require.Equal(t, *qresult1, *q1)
  637. qresult2, ok := qresults[1].(*ctypes.ResultABCIQuery)
  638. require.True(t, ok)
  639. require.Equal(t, *qresult2, *q2)
  640. require.Equal(t, qresult1.Response.Key, k1)
  641. require.Equal(t, qresult2.Response.Key, k2)
  642. require.Equal(t, qresult1.Response.Value, v1)
  643. require.Equal(t, qresult2.Response.Value, v2)
  644. }
  645. func TestBatchedJSONRPCCallsCancellation(t *testing.T) {
  646. c := getHTTPClient()
  647. _, _, tx1 := MakeTxKV()
  648. _, _, tx2 := MakeTxKV()
  649. batch := c.NewBatch()
  650. _, err := batch.BroadcastTxCommit(tx1)
  651. require.NoError(t, err)
  652. _, err = batch.BroadcastTxCommit(tx2)
  653. require.NoError(t, err)
  654. // we should have 2 requests waiting
  655. require.Equal(t, 2, batch.Count())
  656. // we want to make sure we cleared 2 pending requests
  657. require.Equal(t, 2, batch.Clear())
  658. // now there should be no batched requests
  659. require.Equal(t, 0, batch.Count())
  660. }
  661. func TestSendingEmptyJSONRPCRequestBatch(t *testing.T) {
  662. c := getHTTPClient()
  663. batch := c.NewBatch()
  664. _, err := batch.Send()
  665. require.Error(t, err, "sending an empty batch of JSON RPC requests should result in an error")
  666. }
  667. func TestClearingEmptyJSONRPCRequestBatch(t *testing.T) {
  668. c := getHTTPClient()
  669. batch := c.NewBatch()
  670. require.Zero(t, batch.Clear(), "clearing an empty batch of JSON RPC requests should result in a 0 result")
  671. }
  672. func TestConcurrentJSONRPCBatching(t *testing.T) {
  673. var wg sync.WaitGroup
  674. c := getHTTPClient()
  675. for i := 0; i < 50; i++ {
  676. wg.Add(1)
  677. go func() {
  678. defer wg.Done()
  679. testBatchedJSONRPCCalls(t, c)
  680. }()
  681. }
  682. wg.Wait()
  683. }