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.

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