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.

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