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.

543 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
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
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. "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. mempool := node.MempoolReactor().Mempool
  219. initMempoolSize := mempool.Size()
  220. for i, c := range GetClients() {
  221. _, _, tx := MakeTxKV()
  222. bres, err := c.BroadcastTxSync(tx)
  223. require.Nil(err, "%d: %+v", i, err)
  224. require.Equal(bres.Code, abci.CodeTypeOK) // FIXME
  225. require.Equal(initMempoolSize+1, mempool.Size())
  226. txs := mempool.ReapMaxTxs(len(tx))
  227. require.EqualValues(tx, txs[0])
  228. mempool.Flush()
  229. }
  230. }
  231. func TestBroadcastTxCommit(t *testing.T) {
  232. require := require.New(t)
  233. mempool := node.MempoolReactor().Mempool
  234. for i, c := range GetClients() {
  235. _, _, tx := MakeTxKV()
  236. bres, err := c.BroadcastTxCommit(tx)
  237. require.Nil(err, "%d: %+v", i, err)
  238. require.True(bres.CheckTx.IsOK())
  239. require.True(bres.DeliverTx.IsOK())
  240. require.Equal(0, mempool.Size())
  241. }
  242. }
  243. func TestUnconfirmedTxs(t *testing.T) {
  244. _, _, tx := MakeTxKV()
  245. mempool := node.MempoolReactor().Mempool
  246. _ = mempool.CheckTx(tx, nil)
  247. for i, c := range GetClients() {
  248. mc, ok := c.(client.MempoolClient)
  249. require.True(t, ok, "%d", i)
  250. res, err := mc.UnconfirmedTxs(1)
  251. require.Nil(t, err, "%d: %+v", i, err)
  252. assert.Equal(t, 1, res.Count)
  253. assert.Equal(t, 1, res.Total)
  254. assert.Equal(t, mempool.TxsBytes(), res.TotalBytes)
  255. assert.Exactly(t, types.Txs{tx}, types.Txs(res.Txs))
  256. }
  257. mempool.Flush()
  258. }
  259. func TestNumUnconfirmedTxs(t *testing.T) {
  260. _, _, tx := MakeTxKV()
  261. mempool := node.MempoolReactor().Mempool
  262. _ = mempool.CheckTx(tx, nil)
  263. mempoolSize := mempool.Size()
  264. for i, c := range GetClients() {
  265. mc, ok := c.(client.MempoolClient)
  266. require.True(t, ok, "%d", i)
  267. res, err := mc.NumUnconfirmedTxs()
  268. require.Nil(t, err, "%d: %+v", i, err)
  269. assert.Equal(t, mempoolSize, res.Count)
  270. assert.Equal(t, mempoolSize, res.Total)
  271. assert.Equal(t, mempool.TxsBytes(), res.TotalBytes)
  272. }
  273. mempool.Flush()
  274. }
  275. func TestTx(t *testing.T) {
  276. // first we broadcast a tx
  277. c := getHTTPClient()
  278. _, _, tx := MakeTxKV()
  279. bres, err := c.BroadcastTxCommit(tx)
  280. require.Nil(t, err, "%+v", err)
  281. txHeight := bres.Height
  282. txHash := bres.Hash
  283. anotherTxHash := types.Tx("a different tx").Hash()
  284. cases := []struct {
  285. valid bool
  286. hash []byte
  287. prove bool
  288. }{
  289. // only valid if correct hash provided
  290. {true, txHash, false},
  291. {true, txHash, true},
  292. {false, anotherTxHash, false},
  293. {false, anotherTxHash, true},
  294. {false, nil, false},
  295. {false, nil, true},
  296. }
  297. for i, c := range GetClients() {
  298. for j, tc := range cases {
  299. t.Logf("client %d, case %d", i, j)
  300. // now we query for the tx.
  301. // since there's only one tx, we know index=0.
  302. ptx, err := c.Tx(tc.hash, tc.prove)
  303. if !tc.valid {
  304. require.NotNil(t, err)
  305. } else {
  306. require.Nil(t, err, "%+v", err)
  307. assert.EqualValues(t, txHeight, ptx.Height)
  308. assert.EqualValues(t, tx, ptx.Tx)
  309. assert.Zero(t, ptx.Index)
  310. assert.True(t, ptx.TxResult.IsOK())
  311. assert.EqualValues(t, txHash, ptx.Hash)
  312. // time to verify the proof
  313. proof := ptx.Proof
  314. if tc.prove && assert.EqualValues(t, tx, proof.Data) {
  315. assert.NoError(t, proof.Proof.Verify(proof.RootHash, txHash))
  316. }
  317. }
  318. }
  319. }
  320. }
  321. func TestTxSearch(t *testing.T) {
  322. // first we broadcast a tx
  323. c := getHTTPClient()
  324. _, _, tx := MakeTxKV()
  325. bres, err := c.BroadcastTxCommit(tx)
  326. require.Nil(t, err, "%+v", err)
  327. txHeight := bres.Height
  328. txHash := bres.Hash
  329. anotherTxHash := types.Tx("a different tx").Hash()
  330. for i, c := range GetClients() {
  331. t.Logf("client %d", i)
  332. // now we query for the tx.
  333. // since there's only one tx, we know index=0.
  334. result, err := c.TxSearch(fmt.Sprintf("tx.hash='%v'", txHash), true, 1, 30)
  335. require.Nil(t, err, "%+v", err)
  336. require.Len(t, result.Txs, 1)
  337. ptx := result.Txs[0]
  338. assert.EqualValues(t, txHeight, ptx.Height)
  339. assert.EqualValues(t, tx, ptx.Tx)
  340. assert.Zero(t, ptx.Index)
  341. assert.True(t, ptx.TxResult.IsOK())
  342. assert.EqualValues(t, txHash, ptx.Hash)
  343. // time to verify the proof
  344. proof := ptx.Proof
  345. if assert.EqualValues(t, tx, proof.Data) {
  346. assert.NoError(t, proof.Proof.Verify(proof.RootHash, txHash))
  347. }
  348. // query by height
  349. result, err = c.TxSearch(fmt.Sprintf("tx.height=%d", txHeight), true, 1, 30)
  350. require.Nil(t, err, "%+v", err)
  351. require.Len(t, result.Txs, 1)
  352. // query for non existing tx
  353. result, err = c.TxSearch(fmt.Sprintf("tx.hash='%X'", anotherTxHash), false, 1, 30)
  354. require.Nil(t, err, "%+v", err)
  355. require.Len(t, result.Txs, 0)
  356. // query using a tag (see kvstore application)
  357. result, err = c.TxSearch("app.creator='Cosmoshi Netowoko'", false, 1, 30)
  358. require.Nil(t, err, "%+v", err)
  359. if len(result.Txs) == 0 {
  360. t.Fatal("expected a lot of transactions")
  361. }
  362. // query using a tag (see kvstore application) and height
  363. result, err = c.TxSearch("app.creator='Cosmoshi Netowoko' AND tx.height<10000", true, 1, 30)
  364. require.Nil(t, err, "%+v", err)
  365. if len(result.Txs) == 0 {
  366. t.Fatal("expected a lot of transactions")
  367. }
  368. // query a non existing tx with page 1 and txsPerPage 1
  369. result, err = c.TxSearch("app.creator='Cosmoshi Neetowoko'", true, 1, 1)
  370. require.Nil(t, err, "%+v", err)
  371. require.Len(t, result.Txs, 0)
  372. }
  373. }
  374. func TestBatchedJSONRPCCalls(t *testing.T) {
  375. c := getHTTPClient()
  376. testBatchedJSONRPCCalls(t, c)
  377. }
  378. func testBatchedJSONRPCCalls(t *testing.T, c *client.HTTP) {
  379. k1, v1, tx1 := MakeTxKV()
  380. k2, v2, tx2 := MakeTxKV()
  381. batch := c.NewBatch()
  382. r1, err := batch.BroadcastTxCommit(tx1)
  383. require.NoError(t, err)
  384. r2, err := batch.BroadcastTxCommit(tx2)
  385. require.NoError(t, err)
  386. require.Equal(t, 2, batch.Count())
  387. bresults, err := batch.Send()
  388. require.NoError(t, err)
  389. require.Len(t, bresults, 2)
  390. require.Equal(t, 0, batch.Count())
  391. bresult1, ok := bresults[0].(*ctypes.ResultBroadcastTxCommit)
  392. require.True(t, ok)
  393. require.Equal(t, *bresult1, *r1)
  394. bresult2, ok := bresults[1].(*ctypes.ResultBroadcastTxCommit)
  395. require.True(t, ok)
  396. require.Equal(t, *bresult2, *r2)
  397. apph := cmn.MaxInt64(bresult1.Height, bresult2.Height) + 1
  398. client.WaitForHeight(c, apph, nil)
  399. q1, err := batch.ABCIQuery("/key", k1)
  400. require.NoError(t, err)
  401. q2, err := batch.ABCIQuery("/key", k2)
  402. require.NoError(t, err)
  403. require.Equal(t, 2, batch.Count())
  404. qresults, err := batch.Send()
  405. require.NoError(t, err)
  406. require.Len(t, qresults, 2)
  407. require.Equal(t, 0, batch.Count())
  408. qresult1, ok := qresults[0].(*ctypes.ResultABCIQuery)
  409. require.True(t, ok)
  410. require.Equal(t, *qresult1, *q1)
  411. qresult2, ok := qresults[1].(*ctypes.ResultABCIQuery)
  412. require.True(t, ok)
  413. require.Equal(t, *qresult2, *q2)
  414. require.Equal(t, qresult1.Response.Key, k1)
  415. require.Equal(t, qresult2.Response.Key, k2)
  416. require.Equal(t, qresult1.Response.Value, v1)
  417. require.Equal(t, qresult2.Response.Value, v2)
  418. }
  419. func TestBatchedJSONRPCCallsCancellation(t *testing.T) {
  420. c := getHTTPClient()
  421. _, _, tx1 := MakeTxKV()
  422. _, _, tx2 := MakeTxKV()
  423. batch := c.NewBatch()
  424. _, err := batch.BroadcastTxCommit(tx1)
  425. require.NoError(t, err)
  426. _, err = batch.BroadcastTxCommit(tx2)
  427. require.NoError(t, err)
  428. // we should have 2 requests waiting
  429. require.Equal(t, 2, batch.Count())
  430. // we want to make sure we cleared 2 pending requests
  431. require.Equal(t, 2, batch.Clear())
  432. // now there should be no batched requests
  433. require.Equal(t, 0, batch.Count())
  434. }
  435. func TestSendingEmptyJSONRPCRequestBatch(t *testing.T) {
  436. c := getHTTPClient()
  437. batch := c.NewBatch()
  438. _, err := batch.Send()
  439. require.Error(t, err, "sending an empty batch of JSON RPC requests should result in an error")
  440. }
  441. func TestClearingEmptyJSONRPCRequestBatch(t *testing.T) {
  442. c := getHTTPClient()
  443. batch := c.NewBatch()
  444. require.Zero(t, batch.Clear(), "clearing an empty batch of JSON RPC requests should result in a 0 result")
  445. }
  446. func TestConcurrentJSONRPCBatching(t *testing.T) {
  447. var wg sync.WaitGroup
  448. c := getHTTPClient()
  449. for i := 0; i < 50; i++ {
  450. wg.Add(1)
  451. go func() {
  452. defer wg.Done()
  453. testBatchedJSONRPCCalls(t, c)
  454. }()
  455. }
  456. wg.Wait()
  457. }