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.

716 lines
20 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
new pubsub package comment out failing consensus tests for now rewrite rpc httpclient to use new pubsub package import pubsub as tmpubsub, query as tmquery make event IDs constants EventKey -> EventTypeKey rename EventsPubsub to PubSub mempool does not use pubsub rename eventsSub to pubsub new subscribe API fix channel size issues and consensus tests bugs refactor rpc client add missing discardFromChan method add mutex rename pubsub to eventBus remove IsRunning from WSRPCConnection interface (not needed) add a comment in broadcastNewRoundStepsAndVotes rename registerEventCallbacks to broadcastNewRoundStepsAndVotes See https://dave.cheney.net/2014/03/19/channel-axioms stop eventBuses after reactor tests remove unnecessary Unsubscribe return subscribe helper function move discardFromChan to where it is used subscribe now returns an err this gives us ability to refuse to subscribe if pubsub is at its max capacity. use context for control overflow cache queries handle err when subscribing in replay_test rename testClientID to testSubscriber extract var set channel buffer capacity to 1 in replay_file fix byzantine_test unsubscribe from single event, not all events refactor httpclient to return events to appropriate channels return failing testReplayCrashBeforeWriteVote test fix TestValidatorSetChanges refactor code a bit fix testReplayCrashBeforeWriteVote add comment fix TestValidatorSetChanges fixes from Bucky's review update comment [ci skip] test TxEventBuffer update changelog fix TestValidatorSetChanges (2nd attempt) only do wg.Done when no errors benchmark event bus create pubsub server inside NewEventBus only expose config params (later if needed) set buffer capacity to 0 so we are not testing cache new tx event format: key = "Tx" plus a tag {"tx.hash": XYZ} This should allow to subscribe to all transactions! or a specific one using a query: "tm.events.type = Tx and tx.hash = '013ABF99434...'" use TimeoutCommit instead of afterPublishEventNewBlockTimeout TimeoutCommit is the time a node waits after committing a block, before it goes into the next height. So it will finish everything from the last block, but then wait a bit. The idea is this gives it time to hear more votes from other validators, to strengthen the commit it includes in the next block. But it also gives it time to hear about new transactions. waitForBlockWithUpdatedVals rewrite WAL crash tests Task: test that we can recover from any WAL crash. Solution: the old tests were relying on event hub being run in the same thread (we were injecting the private validator's last signature). when considering a rewrite, we considered two possible solutions: write a "fuzzy" testing system where WAL is crashing upon receiving a new message, or inject failures and trigger them in tests using something like https://github.com/coreos/gofail. remove sleep no cs.Lock around wal.Save test different cases (empty block, non-empty block, ...) comments add comments test 4 cases: empty block, non-empty block, non-empty block with smaller part size, many blocks fixes as per Bucky's last review reset subscriptions on UnsubscribeAll use a simple counter to track message for which we panicked also, set a smaller part size for all test cases
8 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
  1. package client_test
  2. import (
  3. "bytes"
  4. "fmt"
  5. "math/rand"
  6. "net/http"
  7. "strings"
  8. "sync"
  9. "testing"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/stretchr/testify/require"
  12. abci "github.com/tendermint/tendermint/abci/types"
  13. "github.com/tendermint/tendermint/crypto/ed25519"
  14. "github.com/tendermint/tendermint/crypto/tmhash"
  15. "github.com/tendermint/tendermint/libs/log"
  16. tmmath "github.com/tendermint/tendermint/libs/math"
  17. mempl "github.com/tendermint/tendermint/mempool"
  18. "github.com/tendermint/tendermint/privval"
  19. "github.com/tendermint/tendermint/rpc/client"
  20. ctypes "github.com/tendermint/tendermint/rpc/core/types"
  21. rpcclient "github.com/tendermint/tendermint/rpc/lib/client"
  22. rpctest "github.com/tendermint/tendermint/rpc/test"
  23. "github.com/tendermint/tendermint/types"
  24. )
  25. func getHTTPClient() *client.HTTP {
  26. rpcAddr := rpctest.GetConfig().RPC.ListenAddress
  27. c := client.NewHTTP(rpcAddr, "/websocket")
  28. c.SetLogger(log.TestingLogger())
  29. return c
  30. }
  31. func getLocalClient() *client.Local {
  32. return client.NewLocal(node)
  33. }
  34. // GetClients returns a slice of clients for table-driven tests
  35. func GetClients() []client.Client {
  36. return []client.Client{
  37. getHTTPClient(),
  38. getLocalClient(),
  39. }
  40. }
  41. func TestNilCustomHTTPClient(t *testing.T) {
  42. require.Panics(t, func() {
  43. client.NewHTTPWithClient("http://example.com", "/websocket", nil)
  44. })
  45. require.Panics(t, func() {
  46. rpcclient.NewJSONRPCClientWithHTTPClient("http://example.com", nil)
  47. })
  48. }
  49. func TestCustomHTTPClient(t *testing.T) {
  50. remote := rpctest.GetConfig().RPC.ListenAddress
  51. c := client.NewHTTPWithClient(remote, "/websocket", http.DefaultClient)
  52. status, err := c.Status()
  53. require.NoError(t, err)
  54. require.NotNil(t, status)
  55. }
  56. func TestCorsEnabled(t *testing.T) {
  57. origin := rpctest.GetConfig().RPC.CORSAllowedOrigins[0]
  58. remote := strings.Replace(rpctest.GetConfig().RPC.ListenAddress, "tcp", "http", -1)
  59. req, err := http.NewRequest("GET", remote, nil)
  60. require.Nil(t, err, "%+v", err)
  61. req.Header.Set("Origin", origin)
  62. c := &http.Client{}
  63. resp, err := c.Do(req)
  64. require.Nil(t, err, "%+v", err)
  65. defer resp.Body.Close()
  66. assert.Equal(t, resp.Header.Get("Access-Control-Allow-Origin"), origin)
  67. }
  68. // Make sure status is correct (we connect properly)
  69. func TestStatus(t *testing.T) {
  70. for i, c := range GetClients() {
  71. moniker := rpctest.GetConfig().Moniker
  72. status, err := c.Status()
  73. require.Nil(t, err, "%d: %+v", i, err)
  74. assert.Equal(t, moniker, status.NodeInfo.Moniker)
  75. }
  76. }
  77. // Make sure info is correct (we connect properly)
  78. func TestInfo(t *testing.T) {
  79. for i, c := range GetClients() {
  80. // status, err := c.Status()
  81. // require.Nil(t, err, "%+v", err)
  82. info, err := c.ABCIInfo()
  83. require.Nil(t, err, "%d: %+v", i, err)
  84. // TODO: this is not correct - fix merkleeyes!
  85. // assert.EqualValues(t, status.SyncInfo.LatestBlockHeight, info.Response.LastBlockHeight)
  86. assert.True(t, strings.Contains(info.Response.Data, "size"))
  87. }
  88. }
  89. func TestNetInfo(t *testing.T) {
  90. for i, c := range GetClients() {
  91. nc, ok := c.(client.NetworkClient)
  92. require.True(t, ok, "%d", i)
  93. netinfo, err := nc.NetInfo()
  94. require.Nil(t, err, "%d: %+v", i, err)
  95. assert.True(t, netinfo.Listening)
  96. assert.Equal(t, 0, len(netinfo.Peers))
  97. }
  98. }
  99. func TestDumpConsensusState(t *testing.T) {
  100. for i, c := range GetClients() {
  101. // FIXME: fix server so it doesn't panic on invalid input
  102. nc, ok := c.(client.NetworkClient)
  103. require.True(t, ok, "%d", i)
  104. cons, err := nc.DumpConsensusState()
  105. require.Nil(t, err, "%d: %+v", i, err)
  106. assert.NotEmpty(t, cons.RoundState)
  107. assert.Empty(t, cons.Peers)
  108. }
  109. }
  110. func TestConsensusState(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.ConsensusState()
  116. require.Nil(t, err, "%d: %+v", i, err)
  117. assert.NotEmpty(t, cons.RoundState)
  118. }
  119. }
  120. func TestHealth(t *testing.T) {
  121. for i, c := range GetClients() {
  122. nc, ok := c.(client.NetworkClient)
  123. require.True(t, ok, "%d", i)
  124. _, err := nc.Health()
  125. require.Nil(t, err, "%d: %+v", i, err)
  126. }
  127. }
  128. func TestGenesisAndValidators(t *testing.T) {
  129. for i, c := range GetClients() {
  130. // make sure this is the right genesis file
  131. gen, err := c.Genesis()
  132. require.Nil(t, err, "%d: %+v", i, err)
  133. // get the genesis validator
  134. require.Equal(t, 1, len(gen.Genesis.Validators))
  135. gval := gen.Genesis.Validators[0]
  136. // get the current validators
  137. vals, err := c.Validators(nil, 0, 0)
  138. require.Nil(t, err, "%d: %+v", i, err)
  139. require.Equal(t, 1, len(vals.Validators))
  140. val := vals.Validators[0]
  141. // make sure the current set is also the genesis set
  142. assert.Equal(t, gval.Power, val.VotingPower)
  143. assert.Equal(t, gval.PubKey, val.PubKey)
  144. }
  145. }
  146. func TestABCIQuery(t *testing.T) {
  147. for i, c := range GetClients() {
  148. // write something
  149. k, v, tx := MakeTxKV()
  150. bres, err := c.BroadcastTxCommit(tx)
  151. require.Nil(t, err, "%d: %+v", i, err)
  152. apph := bres.Height + 1 // this is where the tx will be applied to the state
  153. // wait before querying
  154. client.WaitForHeight(c, apph, nil)
  155. res, err := c.ABCIQuery("/key", k)
  156. qres := res.Response
  157. if assert.Nil(t, err) && assert.True(t, qres.IsOK()) {
  158. assert.EqualValues(t, v, qres.Value)
  159. }
  160. }
  161. }
  162. // Make some app checks
  163. func TestAppCalls(t *testing.T) {
  164. assert, require := assert.New(t), require.New(t)
  165. for i, c := range GetClients() {
  166. // get an offset of height to avoid racing and guessing
  167. s, err := c.Status()
  168. require.Nil(err, "%d: %+v", i, err)
  169. // sh is start height or status height
  170. sh := s.SyncInfo.LatestBlockHeight
  171. // look for the future
  172. h := sh + 2
  173. _, err = c.Block(&h)
  174. assert.NotNil(err) // no block yet
  175. // write something
  176. k, v, tx := MakeTxKV()
  177. bres, err := c.BroadcastTxCommit(tx)
  178. require.Nil(err, "%d: %+v", i, err)
  179. require.True(bres.DeliverTx.IsOK())
  180. txh := bres.Height
  181. apph := txh + 1 // this is where the tx will be applied to the state
  182. // wait before querying
  183. if err := client.WaitForHeight(c, apph, nil); err != nil {
  184. t.Error(err)
  185. }
  186. _qres, err := c.ABCIQueryWithOptions("/key", k, client.ABCIQueryOptions{Prove: false})
  187. qres := _qres.Response
  188. if assert.Nil(err) && assert.True(qres.IsOK()) {
  189. assert.Equal(k, qres.Key)
  190. assert.EqualValues(v, qres.Value)
  191. }
  192. // make sure we can lookup the tx with proof
  193. ptx, err := c.Tx(bres.Hash, true)
  194. require.Nil(err, "%d: %+v", i, err)
  195. assert.EqualValues(txh, ptx.Height)
  196. assert.EqualValues(tx, ptx.Tx)
  197. // and we can even check the block is added
  198. block, err := c.Block(&apph)
  199. require.Nil(err, "%d: %+v", i, err)
  200. appHash := block.Block.Header.AppHash
  201. assert.True(len(appHash) > 0)
  202. assert.EqualValues(apph, block.Block.Header.Height)
  203. // now check the results
  204. blockResults, err := c.BlockResults(&txh)
  205. require.Nil(err, "%d: %+v", i, err)
  206. assert.Equal(txh, blockResults.Height)
  207. if assert.Equal(1, len(blockResults.TxsResults)) {
  208. // check success code
  209. assert.EqualValues(0, blockResults.TxsResults[0].Code)
  210. }
  211. // check blockchain info, now that we know there is info
  212. info, err := c.BlockchainInfo(apph, apph)
  213. require.Nil(err, "%d: %+v", i, err)
  214. assert.True(info.LastHeight >= apph)
  215. if assert.Equal(1, len(info.BlockMetas)) {
  216. lastMeta := info.BlockMetas[0]
  217. assert.EqualValues(apph, lastMeta.Header.Height)
  218. blockData := block.Block
  219. assert.Equal(blockData.Header.AppHash, lastMeta.Header.AppHash)
  220. assert.Equal(block.BlockID, lastMeta.BlockID)
  221. }
  222. // and get the corresponding commit with the same apphash
  223. commit, err := c.Commit(&apph)
  224. require.Nil(err, "%d: %+v", i, err)
  225. cappHash := commit.Header.AppHash
  226. assert.Equal(appHash, cappHash)
  227. assert.NotNil(commit.Commit)
  228. // compare the commits (note Commit(2) has commit from Block(3))
  229. h = apph - 1
  230. commit2, err := c.Commit(&h)
  231. require.Nil(err, "%d: %+v", i, err)
  232. assert.Equal(block.Block.LastCommit, commit2.Commit)
  233. // and we got a proof that works!
  234. _pres, err := c.ABCIQueryWithOptions("/key", k, client.ABCIQueryOptions{Prove: true})
  235. pres := _pres.Response
  236. assert.Nil(err)
  237. assert.True(pres.IsOK())
  238. // XXX Test proof
  239. }
  240. }
  241. func TestBroadcastTxSync(t *testing.T) {
  242. require := require.New(t)
  243. // TODO (melekes): use mempool which is set on RPC rather than getting it from node
  244. mempool := node.Mempool()
  245. initMempoolSize := mempool.Size()
  246. for i, c := range GetClients() {
  247. _, _, tx := MakeTxKV()
  248. bres, err := c.BroadcastTxSync(tx)
  249. require.Nil(err, "%d: %+v", i, err)
  250. require.Equal(bres.Code, abci.CodeTypeOK) // FIXME
  251. require.Equal(initMempoolSize+1, mempool.Size())
  252. txs := mempool.ReapMaxTxs(len(tx))
  253. require.EqualValues(tx, txs[0])
  254. mempool.Flush()
  255. }
  256. }
  257. func TestBroadcastTxCommit(t *testing.T) {
  258. require := require.New(t)
  259. mempool := node.Mempool()
  260. for i, c := range GetClients() {
  261. _, _, tx := MakeTxKV()
  262. bres, err := c.BroadcastTxCommit(tx)
  263. require.Nil(err, "%d: %+v", i, err)
  264. require.True(bres.CheckTx.IsOK())
  265. require.True(bres.DeliverTx.IsOK())
  266. require.Equal(0, mempool.Size())
  267. }
  268. }
  269. func TestUnconfirmedTxs(t *testing.T) {
  270. _, _, tx := MakeTxKV()
  271. mempool := node.Mempool()
  272. _ = mempool.CheckTx(tx, nil, mempl.TxInfo{})
  273. for i, c := range GetClients() {
  274. mc, ok := c.(client.MempoolClient)
  275. require.True(t, ok, "%d", i)
  276. res, err := mc.UnconfirmedTxs(1)
  277. require.Nil(t, err, "%d: %+v", i, err)
  278. assert.Equal(t, 1, res.Count)
  279. assert.Equal(t, 1, res.Total)
  280. assert.Equal(t, mempool.TxsBytes(), res.TotalBytes)
  281. assert.Exactly(t, types.Txs{tx}, types.Txs(res.Txs))
  282. }
  283. mempool.Flush()
  284. }
  285. func TestNumUnconfirmedTxs(t *testing.T) {
  286. _, _, tx := MakeTxKV()
  287. mempool := node.Mempool()
  288. _ = mempool.CheckTx(tx, nil, mempl.TxInfo{})
  289. mempoolSize := mempool.Size()
  290. for i, c := range GetClients() {
  291. mc, ok := c.(client.MempoolClient)
  292. require.True(t, ok, "%d", i)
  293. res, err := mc.NumUnconfirmedTxs()
  294. require.Nil(t, err, "%d: %+v", i, err)
  295. assert.Equal(t, mempoolSize, res.Count)
  296. assert.Equal(t, mempoolSize, res.Total)
  297. assert.Equal(t, mempool.TxsBytes(), res.TotalBytes)
  298. }
  299. mempool.Flush()
  300. }
  301. func TestTx(t *testing.T) {
  302. // first we broadcast a tx
  303. c := getHTTPClient()
  304. _, _, tx := MakeTxKV()
  305. bres, err := c.BroadcastTxCommit(tx)
  306. require.Nil(t, err, "%+v", err)
  307. txHeight := bres.Height
  308. txHash := bres.Hash
  309. anotherTxHash := types.Tx("a different tx").Hash()
  310. cases := []struct {
  311. valid bool
  312. prove bool
  313. hash []byte
  314. }{
  315. // only valid if correct hash provided
  316. {true, false, txHash},
  317. {true, true, txHash},
  318. {false, false, anotherTxHash},
  319. {false, true, anotherTxHash},
  320. {false, false, nil},
  321. {false, true, nil},
  322. }
  323. for i, c := range GetClients() {
  324. for j, tc := range cases {
  325. t.Logf("client %d, case %d", i, j)
  326. // now we query for the tx.
  327. // since there's only one tx, we know index=0.
  328. ptx, err := c.Tx(tc.hash, tc.prove)
  329. if !tc.valid {
  330. require.NotNil(t, err)
  331. } else {
  332. require.Nil(t, err, "%+v", err)
  333. assert.EqualValues(t, txHeight, ptx.Height)
  334. assert.EqualValues(t, tx, ptx.Tx)
  335. assert.Zero(t, ptx.Index)
  336. assert.True(t, ptx.TxResult.IsOK())
  337. assert.EqualValues(t, txHash, ptx.Hash)
  338. // time to verify the proof
  339. proof := ptx.Proof
  340. if tc.prove && assert.EqualValues(t, tx, proof.Data) {
  341. assert.NoError(t, proof.Proof.Verify(proof.RootHash, txHash))
  342. }
  343. }
  344. }
  345. }
  346. }
  347. func TestTxSearch(t *testing.T) {
  348. // first we broadcast a tx
  349. c := getHTTPClient()
  350. _, _, tx := MakeTxKV()
  351. bres, err := c.BroadcastTxCommit(tx)
  352. require.Nil(t, err, "%+v", err)
  353. txHeight := bres.Height
  354. txHash := bres.Hash
  355. anotherTxHash := types.Tx("a different tx").Hash()
  356. for i, c := range GetClients() {
  357. t.Logf("client %d", i)
  358. // now we query for the tx.
  359. // since there's only one tx, we know index=0.
  360. result, err := c.TxSearch(fmt.Sprintf("tx.hash='%v'", txHash), true, 1, 30)
  361. require.Nil(t, err, "%+v", err)
  362. require.Len(t, result.Txs, 1)
  363. ptx := result.Txs[0]
  364. assert.EqualValues(t, txHeight, ptx.Height)
  365. assert.EqualValues(t, tx, ptx.Tx)
  366. assert.Zero(t, ptx.Index)
  367. assert.True(t, ptx.TxResult.IsOK())
  368. assert.EqualValues(t, txHash, ptx.Hash)
  369. // time to verify the proof
  370. proof := ptx.Proof
  371. if assert.EqualValues(t, tx, proof.Data) {
  372. assert.NoError(t, proof.Proof.Verify(proof.RootHash, txHash))
  373. }
  374. // query by height
  375. result, err = c.TxSearch(fmt.Sprintf("tx.height=%d", txHeight), true, 1, 30)
  376. require.Nil(t, err, "%+v", err)
  377. require.Len(t, result.Txs, 1)
  378. // query for non existing tx
  379. result, err = c.TxSearch(fmt.Sprintf("tx.hash='%X'", anotherTxHash), false, 1, 30)
  380. require.Nil(t, err, "%+v", err)
  381. require.Len(t, result.Txs, 0)
  382. // query using a compositeKey (see kvstore application)
  383. result, err = c.TxSearch("app.creator='Cosmoshi Netowoko'", false, 1, 30)
  384. require.Nil(t, err, "%+v", err)
  385. if len(result.Txs) == 0 {
  386. t.Fatal("expected a lot of transactions")
  387. }
  388. // query using a compositeKey (see kvstore application) and height
  389. result, err = c.TxSearch("app.creator='Cosmoshi Netowoko' AND tx.height<10000", true, 1, 30)
  390. require.Nil(t, err, "%+v", err)
  391. if len(result.Txs) == 0 {
  392. t.Fatal("expected a lot of transactions")
  393. }
  394. // query a non existing tx with page 1 and txsPerPage 1
  395. result, err = c.TxSearch("app.creator='Cosmoshi Neetowoko'", true, 1, 1)
  396. require.Nil(t, err, "%+v", err)
  397. require.Len(t, result.Txs, 0)
  398. }
  399. }
  400. func deepcpVote(vote *types.Vote) (res *types.Vote) {
  401. res = &types.Vote{
  402. ValidatorAddress: make([]byte, len(vote.ValidatorAddress)),
  403. ValidatorIndex: vote.ValidatorIndex,
  404. Height: vote.Height,
  405. Round: vote.Round,
  406. Type: vote.Type,
  407. BlockID: types.BlockID{
  408. Hash: make([]byte, len(vote.BlockID.Hash)),
  409. PartsHeader: vote.BlockID.PartsHeader,
  410. },
  411. Signature: make([]byte, len(vote.Signature)),
  412. }
  413. copy(res.ValidatorAddress, vote.ValidatorAddress)
  414. copy(res.BlockID.Hash, vote.BlockID.Hash)
  415. copy(res.Signature, vote.Signature)
  416. return
  417. }
  418. func newEvidence(
  419. t *testing.T,
  420. val *privval.FilePV,
  421. vote *types.Vote,
  422. vote2 *types.Vote,
  423. chainID string,
  424. ) types.DuplicateVoteEvidence {
  425. var err error
  426. deepcpVote2 := deepcpVote(vote2)
  427. deepcpVote2.Signature, err = val.Key.PrivKey.Sign(deepcpVote2.SignBytes(chainID))
  428. require.NoError(t, err)
  429. return *types.NewDuplicateVoteEvidence(val.Key.PubKey, vote, deepcpVote2)
  430. }
  431. func makeEvidences(
  432. t *testing.T,
  433. val *privval.FilePV,
  434. chainID string,
  435. ) (ev types.DuplicateVoteEvidence, fakes []types.DuplicateVoteEvidence) {
  436. vote := &types.Vote{
  437. ValidatorAddress: val.Key.Address,
  438. ValidatorIndex: 0,
  439. Height: 1,
  440. Round: 0,
  441. Type: types.PrevoteType,
  442. BlockID: types.BlockID{
  443. Hash: tmhash.Sum([]byte("blockhash")),
  444. PartsHeader: types.PartSetHeader{
  445. Total: 1000,
  446. Hash: tmhash.Sum([]byte("partset")),
  447. },
  448. },
  449. }
  450. var err error
  451. vote.Signature, err = val.Key.PrivKey.Sign(vote.SignBytes(chainID))
  452. require.NoError(t, err)
  453. vote2 := deepcpVote(vote)
  454. vote2.BlockID.Hash = tmhash.Sum([]byte("blockhash2"))
  455. ev = newEvidence(t, val, vote, vote2, chainID)
  456. fakes = make([]types.DuplicateVoteEvidence, 42)
  457. // different address
  458. vote2 = deepcpVote(vote)
  459. for i := 0; i < 10; i++ {
  460. rand.Read(vote2.ValidatorAddress) // nolint: gosec
  461. fakes[i] = newEvidence(t, val, vote, vote2, chainID)
  462. }
  463. // different index
  464. vote2 = deepcpVote(vote)
  465. for i := 10; i < 20; i++ {
  466. vote2.ValidatorIndex = rand.Int()%100 + 1 // nolint: gosec
  467. fakes[i] = newEvidence(t, val, vote, vote2, chainID)
  468. }
  469. // different height
  470. vote2 = deepcpVote(vote)
  471. for i := 20; i < 30; i++ {
  472. vote2.Height = rand.Int63()%1000 + 100 // nolint: gosec
  473. fakes[i] = newEvidence(t, val, vote, vote2, chainID)
  474. }
  475. // different round
  476. vote2 = deepcpVote(vote)
  477. for i := 30; i < 40; i++ {
  478. vote2.Round = rand.Int()%10 + 1 // nolint: gosec
  479. fakes[i] = newEvidence(t, val, vote, vote2, chainID)
  480. }
  481. // different type
  482. vote2 = deepcpVote(vote)
  483. vote2.Type = types.PrecommitType
  484. fakes[40] = newEvidence(t, val, vote, vote2, chainID)
  485. // exactly same vote
  486. vote2 = deepcpVote(vote)
  487. fakes[41] = newEvidence(t, val, vote, vote2, chainID)
  488. return ev, fakes
  489. }
  490. func TestBroadcastEvidenceDuplicateVote(t *testing.T) {
  491. config := rpctest.GetConfig()
  492. chainID := config.ChainID()
  493. pvKeyFile := config.PrivValidatorKeyFile()
  494. pvKeyStateFile := config.PrivValidatorStateFile()
  495. pv := privval.LoadOrGenFilePV(pvKeyFile, pvKeyStateFile)
  496. ev, fakes := makeEvidences(t, pv, chainID)
  497. t.Logf("evidence %v", ev)
  498. for i, c := range GetClients() {
  499. t.Logf("client %d", i)
  500. result, err := c.BroadcastEvidence(&ev)
  501. require.Nil(t, err)
  502. require.Equal(t, ev.Hash(), result.Hash, "Invalid response, result %+v", result)
  503. status, err := c.Status()
  504. require.NoError(t, err)
  505. client.WaitForHeight(c, status.SyncInfo.LatestBlockHeight+2, nil)
  506. ed25519pub := ev.PubKey.(ed25519.PubKeyEd25519)
  507. rawpub := ed25519pub[:]
  508. result2, err := c.ABCIQuery("/val", rawpub)
  509. require.Nil(t, err, "Error querying evidence, err %v", err)
  510. qres := result2.Response
  511. require.True(t, qres.IsOK(), "Response not OK")
  512. var v abci.ValidatorUpdate
  513. err = abci.ReadMessage(bytes.NewReader(qres.Value), &v)
  514. require.NoError(t, err, "Error reading query result, value %v", qres.Value)
  515. require.EqualValues(t, rawpub, v.PubKey.Data, "Stored PubKey not equal with expected, value %v", string(qres.Value))
  516. require.Equal(t, int64(9), v.Power, "Stored Power not equal with expected, value %v", string(qres.Value))
  517. for _, fake := range fakes {
  518. _, err := c.BroadcastEvidence(&types.DuplicateVoteEvidence{
  519. PubKey: fake.PubKey,
  520. VoteA: fake.VoteA,
  521. VoteB: fake.VoteB})
  522. require.Error(t, err, "Broadcasting fake evidence succeed: %s", fake.String())
  523. }
  524. }
  525. }
  526. func TestBatchedJSONRPCCalls(t *testing.T) {
  527. c := getHTTPClient()
  528. testBatchedJSONRPCCalls(t, c)
  529. }
  530. func testBatchedJSONRPCCalls(t *testing.T, c *client.HTTP) {
  531. k1, v1, tx1 := MakeTxKV()
  532. k2, v2, tx2 := MakeTxKV()
  533. batch := c.NewBatch()
  534. r1, err := batch.BroadcastTxCommit(tx1)
  535. require.NoError(t, err)
  536. r2, err := batch.BroadcastTxCommit(tx2)
  537. require.NoError(t, err)
  538. require.Equal(t, 2, batch.Count())
  539. bresults, err := batch.Send()
  540. require.NoError(t, err)
  541. require.Len(t, bresults, 2)
  542. require.Equal(t, 0, batch.Count())
  543. bresult1, ok := bresults[0].(*ctypes.ResultBroadcastTxCommit)
  544. require.True(t, ok)
  545. require.Equal(t, *bresult1, *r1)
  546. bresult2, ok := bresults[1].(*ctypes.ResultBroadcastTxCommit)
  547. require.True(t, ok)
  548. require.Equal(t, *bresult2, *r2)
  549. apph := tmmath.MaxInt64(bresult1.Height, bresult2.Height) + 1
  550. client.WaitForHeight(c, apph, nil)
  551. q1, err := batch.ABCIQuery("/key", k1)
  552. require.NoError(t, err)
  553. q2, err := batch.ABCIQuery("/key", k2)
  554. require.NoError(t, err)
  555. require.Equal(t, 2, batch.Count())
  556. qresults, err := batch.Send()
  557. require.NoError(t, err)
  558. require.Len(t, qresults, 2)
  559. require.Equal(t, 0, batch.Count())
  560. qresult1, ok := qresults[0].(*ctypes.ResultABCIQuery)
  561. require.True(t, ok)
  562. require.Equal(t, *qresult1, *q1)
  563. qresult2, ok := qresults[1].(*ctypes.ResultABCIQuery)
  564. require.True(t, ok)
  565. require.Equal(t, *qresult2, *q2)
  566. require.Equal(t, qresult1.Response.Key, k1)
  567. require.Equal(t, qresult2.Response.Key, k2)
  568. require.Equal(t, qresult1.Response.Value, v1)
  569. require.Equal(t, qresult2.Response.Value, v2)
  570. }
  571. func TestBatchedJSONRPCCallsCancellation(t *testing.T) {
  572. c := getHTTPClient()
  573. _, _, tx1 := MakeTxKV()
  574. _, _, tx2 := MakeTxKV()
  575. batch := c.NewBatch()
  576. _, err := batch.BroadcastTxCommit(tx1)
  577. require.NoError(t, err)
  578. _, err = batch.BroadcastTxCommit(tx2)
  579. require.NoError(t, err)
  580. // we should have 2 requests waiting
  581. require.Equal(t, 2, batch.Count())
  582. // we want to make sure we cleared 2 pending requests
  583. require.Equal(t, 2, batch.Clear())
  584. // now there should be no batched requests
  585. require.Equal(t, 0, batch.Count())
  586. }
  587. func TestSendingEmptyJSONRPCRequestBatch(t *testing.T) {
  588. c := getHTTPClient()
  589. batch := c.NewBatch()
  590. _, err := batch.Send()
  591. require.Error(t, err, "sending an empty batch of JSON RPC requests should result in an error")
  592. }
  593. func TestClearingEmptyJSONRPCRequestBatch(t *testing.T) {
  594. c := getHTTPClient()
  595. batch := c.NewBatch()
  596. require.Zero(t, batch.Clear(), "clearing an empty batch of JSON RPC requests should result in a 0 result")
  597. }
  598. func TestConcurrentJSONRPCBatching(t *testing.T) {
  599. var wg sync.WaitGroup
  600. c := getHTTPClient()
  601. for i := 0; i < 50; i++ {
  602. wg.Add(1)
  603. go func() {
  604. defer wg.Done()
  605. testBatchedJSONRPCCalls(t, c)
  606. }()
  607. }
  608. wg.Wait()
  609. }