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
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
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
5 years ago
7 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
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 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
5 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
5 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
5 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
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
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
5 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. cmn "github.com/tendermint/tendermint/libs/common"
  16. "github.com/tendermint/tendermint/privval"
  17. "github.com/tendermint/tendermint/rpc/client"
  18. ctypes "github.com/tendermint/tendermint/rpc/core/types"
  19. rpcclient "github.com/tendermint/tendermint/rpc/lib/client"
  20. rpctest "github.com/tendermint/tendermint/rpc/test"
  21. "github.com/tendermint/tendermint/types"
  22. )
  23. func getHTTPClient() *client.HTTP {
  24. rpcAddr := rpctest.GetConfig().RPC.ListenAddress
  25. return client.NewHTTP(rpcAddr, "/websocket")
  26. }
  27. func getLocalClient() *client.Local {
  28. return client.NewLocal(node)
  29. }
  30. // GetClients returns a slice of clients for table-driven tests
  31. func GetClients() []client.Client {
  32. return []client.Client{
  33. getHTTPClient(),
  34. getLocalClient(),
  35. }
  36. }
  37. func TestNilCustomHTTPClient(t *testing.T) {
  38. require.Panics(t, func() {
  39. client.NewHTTPWithClient("http://example.com", "/websocket", nil)
  40. })
  41. require.Panics(t, func() {
  42. rpcclient.NewJSONRPCClientWithHTTPClient("http://example.com", nil)
  43. })
  44. }
  45. func TestCustomHTTPClient(t *testing.T) {
  46. remote := rpctest.GetConfig().RPC.ListenAddress
  47. c := client.NewHTTPWithClient(remote, "/websocket", http.DefaultClient)
  48. status, err := c.Status()
  49. require.NoError(t, err)
  50. require.NotNil(t, status)
  51. }
  52. func TestCorsEnabled(t *testing.T) {
  53. origin := rpctest.GetConfig().RPC.CORSAllowedOrigins[0]
  54. remote := strings.Replace(rpctest.GetConfig().RPC.ListenAddress, "tcp", "http", -1)
  55. req, err := http.NewRequest("GET", remote, nil)
  56. require.Nil(t, err, "%+v", err)
  57. req.Header.Set("Origin", origin)
  58. c := &http.Client{}
  59. resp, err := c.Do(req)
  60. require.Nil(t, err, "%+v", err)
  61. defer resp.Body.Close()
  62. assert.Equal(t, resp.Header.Get("Access-Control-Allow-Origin"), origin)
  63. }
  64. // Make sure status is correct (we connect properly)
  65. func TestStatus(t *testing.T) {
  66. for i, c := range GetClients() {
  67. moniker := rpctest.GetConfig().Moniker
  68. status, err := c.Status()
  69. require.Nil(t, err, "%d: %+v", i, err)
  70. assert.Equal(t, moniker, status.NodeInfo.Moniker)
  71. }
  72. }
  73. // Make sure info is correct (we connect properly)
  74. func TestInfo(t *testing.T) {
  75. for i, c := range GetClients() {
  76. // status, err := c.Status()
  77. // require.Nil(t, err, "%+v", err)
  78. info, err := c.ABCIInfo()
  79. require.Nil(t, err, "%d: %+v", i, err)
  80. // TODO: this is not correct - fix merkleeyes!
  81. // assert.EqualValues(t, status.SyncInfo.LatestBlockHeight, info.Response.LastBlockHeight)
  82. assert.True(t, strings.Contains(info.Response.Data, "size"))
  83. }
  84. }
  85. func TestNetInfo(t *testing.T) {
  86. for i, c := range GetClients() {
  87. nc, ok := c.(client.NetworkClient)
  88. require.True(t, ok, "%d", i)
  89. netinfo, err := nc.NetInfo()
  90. require.Nil(t, err, "%d: %+v", i, err)
  91. assert.True(t, netinfo.Listening)
  92. assert.Equal(t, 0, len(netinfo.Peers))
  93. }
  94. }
  95. func TestDumpConsensusState(t *testing.T) {
  96. for i, c := range GetClients() {
  97. // FIXME: fix server so it doesn't panic on invalid input
  98. nc, ok := c.(client.NetworkClient)
  99. require.True(t, ok, "%d", i)
  100. cons, err := nc.DumpConsensusState()
  101. require.Nil(t, err, "%d: %+v", i, err)
  102. assert.NotEmpty(t, cons.RoundState)
  103. assert.Empty(t, cons.Peers)
  104. }
  105. }
  106. func TestConsensusState(t *testing.T) {
  107. for i, c := range GetClients() {
  108. // FIXME: fix server so it doesn't panic on invalid input
  109. nc, ok := c.(client.NetworkClient)
  110. require.True(t, ok, "%d", i)
  111. cons, err := nc.ConsensusState()
  112. require.Nil(t, err, "%d: %+v", i, err)
  113. assert.NotEmpty(t, cons.RoundState)
  114. }
  115. }
  116. func TestHealth(t *testing.T) {
  117. for i, c := range GetClients() {
  118. nc, ok := c.(client.NetworkClient)
  119. require.True(t, ok, "%d", i)
  120. _, err := nc.Health()
  121. require.Nil(t, err, "%d: %+v", i, err)
  122. }
  123. }
  124. func TestGenesisAndValidators(t *testing.T) {
  125. for i, c := range GetClients() {
  126. // make sure this is the right genesis file
  127. gen, err := c.Genesis()
  128. require.Nil(t, err, "%d: %+v", i, err)
  129. // get the genesis validator
  130. require.Equal(t, 1, len(gen.Genesis.Validators))
  131. gval := gen.Genesis.Validators[0]
  132. // get the current validators
  133. vals, err := c.Validators(nil)
  134. require.Nil(t, err, "%d: %+v", i, err)
  135. require.Equal(t, 1, len(vals.Validators))
  136. val := vals.Validators[0]
  137. // make sure the current set is also the genesis set
  138. assert.Equal(t, gval.Power, val.VotingPower)
  139. assert.Equal(t, gval.PubKey, val.PubKey)
  140. }
  141. }
  142. func TestABCIQuery(t *testing.T) {
  143. for i, c := range GetClients() {
  144. // write something
  145. k, v, tx := MakeTxKV()
  146. bres, err := c.BroadcastTxCommit(tx)
  147. require.Nil(t, err, "%d: %+v", i, err)
  148. apph := bres.Height + 1 // this is where the tx will be applied to the state
  149. // wait before querying
  150. client.WaitForHeight(c, apph, nil)
  151. res, err := c.ABCIQuery("/key", k)
  152. qres := res.Response
  153. if assert.Nil(t, err) && assert.True(t, qres.IsOK()) {
  154. assert.EqualValues(t, v, qres.Value)
  155. }
  156. }
  157. }
  158. // Make some app checks
  159. func TestAppCalls(t *testing.T) {
  160. assert, require := assert.New(t), require.New(t)
  161. for i, c := range GetClients() {
  162. // get an offset of height to avoid racing and guessing
  163. s, err := c.Status()
  164. require.Nil(err, "%d: %+v", i, err)
  165. // sh is start height or status height
  166. sh := s.SyncInfo.LatestBlockHeight
  167. // look for the future
  168. h := sh + 2
  169. _, err = c.Block(&h)
  170. assert.NotNil(err) // no block yet
  171. // write something
  172. k, v, tx := MakeTxKV()
  173. bres, err := c.BroadcastTxCommit(tx)
  174. require.Nil(err, "%d: %+v", i, err)
  175. require.True(bres.DeliverTx.IsOK())
  176. txh := bres.Height
  177. apph := txh + 1 // this is where the tx will be applied to the state
  178. // wait before querying
  179. if err := client.WaitForHeight(c, apph, nil); err != nil {
  180. t.Error(err)
  181. }
  182. _qres, err := c.ABCIQueryWithOptions("/key", k, client.ABCIQueryOptions{Prove: false})
  183. qres := _qres.Response
  184. if assert.Nil(err) && assert.True(qres.IsOK()) {
  185. assert.Equal(k, qres.Key)
  186. assert.EqualValues(v, qres.Value)
  187. }
  188. // make sure we can lookup the tx with proof
  189. ptx, err := c.Tx(bres.Hash, true)
  190. require.Nil(err, "%d: %+v", i, err)
  191. assert.EqualValues(txh, ptx.Height)
  192. assert.EqualValues(tx, ptx.Tx)
  193. // and we can even check the block is added
  194. block, err := c.Block(&apph)
  195. require.Nil(err, "%d: %+v", i, err)
  196. appHash := block.BlockMeta.Header.AppHash
  197. assert.True(len(appHash) > 0)
  198. assert.EqualValues(apph, block.BlockMeta.Header.Height)
  199. // now check the results
  200. blockResults, err := c.BlockResults(&txh)
  201. require.Nil(err, "%d: %+v", i, err)
  202. assert.Equal(txh, blockResults.Height)
  203. if assert.Equal(1, len(blockResults.Results.DeliverTx)) {
  204. // check success code
  205. assert.EqualValues(0, blockResults.Results.DeliverTx[0].Code)
  206. }
  207. // check blockchain info, now that we know there is info
  208. info, err := c.BlockchainInfo(apph, apph)
  209. require.Nil(err, "%d: %+v", i, err)
  210. assert.True(info.LastHeight >= apph)
  211. if assert.Equal(1, len(info.BlockMetas)) {
  212. lastMeta := info.BlockMetas[0]
  213. assert.EqualValues(apph, lastMeta.Header.Height)
  214. bMeta := block.BlockMeta
  215. assert.Equal(bMeta.Header.AppHash, lastMeta.Header.AppHash)
  216. assert.Equal(bMeta.BlockID, lastMeta.BlockID)
  217. }
  218. // and get the corresponding commit with the same apphash
  219. commit, err := c.Commit(&apph)
  220. require.Nil(err, "%d: %+v", i, err)
  221. cappHash := commit.Header.AppHash
  222. assert.Equal(appHash, cappHash)
  223. assert.NotNil(commit.Commit)
  224. // compare the commits (note Commit(2) has commit from Block(3))
  225. h = apph - 1
  226. commit2, err := c.Commit(&h)
  227. require.Nil(err, "%d: %+v", i, err)
  228. assert.Equal(block.Block.LastCommit, commit2.Commit)
  229. // and we got a proof that works!
  230. _pres, err := c.ABCIQueryWithOptions("/key", k, client.ABCIQueryOptions{Prove: true})
  231. pres := _pres.Response
  232. assert.Nil(err)
  233. assert.True(pres.IsOK())
  234. // XXX Test proof
  235. }
  236. }
  237. func TestBroadcastTxSync(t *testing.T) {
  238. require := require.New(t)
  239. // TODO (melekes): use mempool which is set on RPC rather than getting it from node
  240. mempool := node.Mempool()
  241. initMempoolSize := mempool.Size()
  242. for i, c := range GetClients() {
  243. _, _, tx := MakeTxKV()
  244. bres, err := c.BroadcastTxSync(tx)
  245. require.Nil(err, "%d: %+v", i, err)
  246. require.Equal(bres.Code, abci.CodeTypeOK) // FIXME
  247. require.Equal(initMempoolSize+1, mempool.Size())
  248. txs := mempool.ReapMaxTxs(len(tx))
  249. require.EqualValues(tx, txs[0])
  250. mempool.Flush()
  251. }
  252. }
  253. func TestBroadcastTxCommit(t *testing.T) {
  254. require := require.New(t)
  255. mempool := node.Mempool()
  256. for i, c := range GetClients() {
  257. _, _, tx := MakeTxKV()
  258. bres, err := c.BroadcastTxCommit(tx)
  259. require.Nil(err, "%d: %+v", i, err)
  260. require.True(bres.CheckTx.IsOK())
  261. require.True(bres.DeliverTx.IsOK())
  262. require.Equal(0, mempool.Size())
  263. }
  264. }
  265. func TestUnconfirmedTxs(t *testing.T) {
  266. _, _, tx := MakeTxKV()
  267. mempool := node.Mempool()
  268. _ = mempool.CheckTx(tx, nil)
  269. for i, c := range GetClients() {
  270. mc, ok := c.(client.MempoolClient)
  271. require.True(t, ok, "%d", i)
  272. res, err := mc.UnconfirmedTxs(1)
  273. require.Nil(t, err, "%d: %+v", i, err)
  274. assert.Equal(t, 1, res.Count)
  275. assert.Equal(t, 1, res.Total)
  276. assert.Equal(t, mempool.TxsBytes(), res.TotalBytes)
  277. assert.Exactly(t, types.Txs{tx}, types.Txs(res.Txs))
  278. }
  279. mempool.Flush()
  280. }
  281. func TestNumUnconfirmedTxs(t *testing.T) {
  282. _, _, tx := MakeTxKV()
  283. mempool := node.Mempool()
  284. _ = mempool.CheckTx(tx, nil)
  285. mempoolSize := mempool.Size()
  286. for i, c := range GetClients() {
  287. mc, ok := c.(client.MempoolClient)
  288. require.True(t, ok, "%d", i)
  289. res, err := mc.NumUnconfirmedTxs()
  290. require.Nil(t, err, "%d: %+v", i, err)
  291. assert.Equal(t, mempoolSize, res.Count)
  292. assert.Equal(t, mempoolSize, res.Total)
  293. assert.Equal(t, mempool.TxsBytes(), res.TotalBytes)
  294. }
  295. mempool.Flush()
  296. }
  297. func TestTx(t *testing.T) {
  298. // first we broadcast a tx
  299. c := getHTTPClient()
  300. _, _, tx := MakeTxKV()
  301. bres, err := c.BroadcastTxCommit(tx)
  302. require.Nil(t, err, "%+v", err)
  303. txHeight := bres.Height
  304. txHash := bres.Hash
  305. anotherTxHash := types.Tx("a different tx").Hash()
  306. cases := []struct {
  307. valid bool
  308. prove bool
  309. hash []byte
  310. }{
  311. // only valid if correct hash provided
  312. {true, false, txHash},
  313. {true, true, txHash},
  314. {false, false, anotherTxHash},
  315. {false, true, anotherTxHash},
  316. {false, false, nil},
  317. {false, true, nil},
  318. }
  319. for i, c := range GetClients() {
  320. for j, tc := range cases {
  321. t.Logf("client %d, case %d", i, j)
  322. // now we query for the tx.
  323. // since there's only one tx, we know index=0.
  324. ptx, err := c.Tx(tc.hash, tc.prove)
  325. if !tc.valid {
  326. require.NotNil(t, err)
  327. } else {
  328. require.Nil(t, err, "%+v", err)
  329. assert.EqualValues(t, txHeight, ptx.Height)
  330. assert.EqualValues(t, tx, ptx.Tx)
  331. assert.Zero(t, ptx.Index)
  332. assert.True(t, ptx.TxResult.IsOK())
  333. assert.EqualValues(t, txHash, ptx.Hash)
  334. // time to verify the proof
  335. proof := ptx.Proof
  336. if tc.prove && assert.EqualValues(t, tx, proof.Data) {
  337. assert.NoError(t, proof.Proof.Verify(proof.RootHash, txHash))
  338. }
  339. }
  340. }
  341. }
  342. }
  343. func TestTxSearch(t *testing.T) {
  344. // first we broadcast a tx
  345. c := getHTTPClient()
  346. _, _, tx := MakeTxKV()
  347. bres, err := c.BroadcastTxCommit(tx)
  348. require.Nil(t, err, "%+v", err)
  349. txHeight := bres.Height
  350. txHash := bres.Hash
  351. anotherTxHash := types.Tx("a different tx").Hash()
  352. for i, c := range GetClients() {
  353. t.Logf("client %d", i)
  354. // now we query for the tx.
  355. // since there's only one tx, we know index=0.
  356. result, err := c.TxSearch(fmt.Sprintf("tx.hash='%v'", txHash), true, 1, 30)
  357. require.Nil(t, err, "%+v", err)
  358. require.Len(t, result.Txs, 1)
  359. ptx := result.Txs[0]
  360. assert.EqualValues(t, txHeight, ptx.Height)
  361. assert.EqualValues(t, tx, ptx.Tx)
  362. assert.Zero(t, ptx.Index)
  363. assert.True(t, ptx.TxResult.IsOK())
  364. assert.EqualValues(t, txHash, ptx.Hash)
  365. // time to verify the proof
  366. proof := ptx.Proof
  367. if assert.EqualValues(t, tx, proof.Data) {
  368. assert.NoError(t, proof.Proof.Verify(proof.RootHash, txHash))
  369. }
  370. // query by height
  371. result, err = c.TxSearch(fmt.Sprintf("tx.height=%d", txHeight), true, 1, 30)
  372. require.Nil(t, err, "%+v", err)
  373. require.Len(t, result.Txs, 1)
  374. // query for non existing tx
  375. result, err = c.TxSearch(fmt.Sprintf("tx.hash='%X'", anotherTxHash), false, 1, 30)
  376. require.Nil(t, err, "%+v", err)
  377. require.Len(t, result.Txs, 0)
  378. // query using a tag (see kvstore application)
  379. result, err = c.TxSearch("app.creator='Cosmoshi Netowoko'", false, 1, 30)
  380. require.Nil(t, err, "%+v", err)
  381. if len(result.Txs) == 0 {
  382. t.Fatal("expected a lot of transactions")
  383. }
  384. // query using a tag (see kvstore application) and height
  385. result, err = c.TxSearch("app.creator='Cosmoshi Netowoko' AND tx.height<10000", true, 1, 30)
  386. require.Nil(t, err, "%+v", err)
  387. if len(result.Txs) == 0 {
  388. t.Fatal("expected a lot of transactions")
  389. }
  390. // query a non existing tx with page 1 and txsPerPage 1
  391. result, err = c.TxSearch("app.creator='Cosmoshi Neetowoko'", true, 1, 1)
  392. require.Nil(t, err, "%+v", err)
  393. require.Len(t, result.Txs, 0)
  394. }
  395. }
  396. func deepcpVote(vote *types.Vote) (res *types.Vote) {
  397. res = &types.Vote{
  398. ValidatorAddress: make([]byte, len(vote.ValidatorAddress)),
  399. ValidatorIndex: vote.ValidatorIndex,
  400. Height: vote.Height,
  401. Round: vote.Round,
  402. Type: vote.Type,
  403. BlockID: types.BlockID{
  404. Hash: make([]byte, len(vote.BlockID.Hash)),
  405. PartsHeader: vote.BlockID.PartsHeader,
  406. },
  407. Signature: make([]byte, len(vote.Signature)),
  408. }
  409. copy(res.ValidatorAddress, vote.ValidatorAddress)
  410. copy(res.BlockID.Hash, vote.BlockID.Hash)
  411. copy(res.Signature, vote.Signature)
  412. return
  413. }
  414. func newEvidence(
  415. t *testing.T,
  416. val *privval.FilePV,
  417. vote *types.Vote,
  418. vote2 *types.Vote,
  419. chainID string,
  420. ) types.DuplicateVoteEvidence {
  421. var err error
  422. vote2_ := deepcpVote(vote2)
  423. vote2_.Signature, err = val.Key.PrivKey.Sign(vote2_.SignBytes(chainID))
  424. require.NoError(t, err)
  425. return types.DuplicateVoteEvidence{
  426. PubKey: val.Key.PubKey,
  427. VoteA: vote,
  428. VoteB: vote2_,
  429. }
  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(&types.DuplicateVoteEvidence{PubKey: ev.PubKey, VoteA: ev.VoteA, VoteB: ev.VoteB})
  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 := cmn.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. }