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.

267 lines
6.8 KiB

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
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
8 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
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
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
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
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
8 years ago
8 years ago
9 years ago
  1. package core
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "github.com/pkg/errors"
  7. abci "github.com/tendermint/abci/types"
  8. data "github.com/tendermint/go-wire/data"
  9. ctypes "github.com/tendermint/tendermint/rpc/core/types"
  10. "github.com/tendermint/tendermint/types"
  11. )
  12. //-----------------------------------------------------------------------------
  13. // NOTE: tx should be signed, but this is only checked at the app level (not by Tendermint!)
  14. // Returns right away, with no response
  15. //
  16. // ```shell
  17. // curl 'localhost:46657/broadcast_tx_async?tx="123"'
  18. // ```
  19. //
  20. // ```go
  21. // client := client.NewHTTP("tcp://0.0.0.0:46657", "/websocket")
  22. // result, err := client.BroadcastTxAsync("123")
  23. // ```
  24. //
  25. // > The above command returns JSON structured like this:
  26. //
  27. // ```json
  28. // {
  29. // "error": "",
  30. // "result": {
  31. // "hash": "E39AAB7A537ABAA237831742DCE1117F187C3C52",
  32. // "log": "",
  33. // "data": "",
  34. // "code": 0
  35. // },
  36. // "id": "",
  37. // "jsonrpc": "2.0"
  38. // }
  39. // ```
  40. //
  41. // ### Query Parameters
  42. //
  43. // | Parameter | Type | Default | Required | Description |
  44. // |-----------+------+---------+----------+-----------------|
  45. // | tx | Tx | nil | true | The transaction |
  46. func BroadcastTxAsync(tx types.Tx) (*ctypes.ResultBroadcastTx, error) {
  47. err := mempool.CheckTx(tx, nil)
  48. if err != nil {
  49. return nil, fmt.Errorf("Error broadcasting transaction: %v", err)
  50. }
  51. return &ctypes.ResultBroadcastTx{Hash: tx.Hash()}, nil
  52. }
  53. // Returns with the response from CheckTx.
  54. //
  55. // ```shell
  56. // curl 'localhost:46657/broadcast_tx_sync?tx="456"'
  57. // ```
  58. //
  59. // ```go
  60. // client := client.NewHTTP("tcp://0.0.0.0:46657", "/websocket")
  61. // result, err := client.BroadcastTxSync("456")
  62. // ```
  63. //
  64. // > The above command returns JSON structured like this:
  65. //
  66. // ```json
  67. // {
  68. // "jsonrpc": "2.0",
  69. // "id": "",
  70. // "result": {
  71. // "code": 0,
  72. // "data": "",
  73. // "log": "",
  74. // "hash": "0D33F2F03A5234F38706E43004489E061AC40A2E"
  75. // },
  76. // "error": ""
  77. // }
  78. // ```
  79. //
  80. // ### Query Parameters
  81. //
  82. // | Parameter | Type | Default | Required | Description |
  83. // |-----------+------+---------+----------+-----------------|
  84. // | tx | Tx | nil | true | The transaction |
  85. func BroadcastTxSync(tx types.Tx) (*ctypes.ResultBroadcastTx, error) {
  86. resCh := make(chan *abci.Response, 1)
  87. err := mempool.CheckTx(tx, func(res *abci.Response) {
  88. resCh <- res
  89. })
  90. if err != nil {
  91. return nil, fmt.Errorf("Error broadcasting transaction: %v", err)
  92. }
  93. res := <-resCh
  94. r := res.GetCheckTx()
  95. return &ctypes.ResultBroadcastTx{
  96. Code: r.Code,
  97. Data: r.Data,
  98. Log: r.Log,
  99. Hash: tx.Hash(),
  100. }, nil
  101. }
  102. // CONTRACT: only returns error if mempool.BroadcastTx errs (ie. problem with the app)
  103. // or if we timeout waiting for tx to commit.
  104. // If CheckTx or DeliverTx fail, no error will be returned, but the returned result
  105. // will contain a non-OK ABCI code.
  106. //
  107. // ```shell
  108. // curl 'localhost:46657/broadcast_tx_commit?tx="789"'
  109. // ```
  110. //
  111. // ```go
  112. // client := client.NewHTTP("tcp://0.0.0.0:46657", "/websocket")
  113. // result, err := client.BroadcastTxCommit("789")
  114. // ```
  115. //
  116. // > The above command returns JSON structured like this:
  117. //
  118. // ```json
  119. // {
  120. // "error": "",
  121. // "result": {
  122. // "height": 26682,
  123. // "hash": "75CA0F856A4DA078FC4911580360E70CEFB2EBEE",
  124. // "deliver_tx": {
  125. // "log": "",
  126. // "data": "",
  127. // "code": 0
  128. // },
  129. // "check_tx": {
  130. // "log": "",
  131. // "data": "",
  132. // "code": 0
  133. // }
  134. // },
  135. // "id": "",
  136. // "jsonrpc": "2.0"
  137. // }
  138. // ```
  139. //
  140. // ### Query Parameters
  141. //
  142. // | Parameter | Type | Default | Required | Description |
  143. // |-----------+------+---------+----------+-----------------|
  144. // | tx | Tx | nil | true | The transaction |
  145. func BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) {
  146. // subscribe to tx being committed in block
  147. ctx, cancel := context.WithTimeout(context.Background(), subscribeTimeout)
  148. defer cancel()
  149. deliverTxResCh := make(chan interface{})
  150. q := types.EventQueryTxFor(tx)
  151. err := eventBus.Subscribe(ctx, "mempool", q, deliverTxResCh)
  152. if err != nil {
  153. err = errors.Wrap(err, "failed to subscribe to tx")
  154. logger.Error("Error on broadcastTxCommit", "err", err)
  155. return nil, fmt.Errorf("Error on broadcastTxCommit: %v", err)
  156. }
  157. defer eventBus.Unsubscribe(context.Background(), "mempool", q)
  158. // broadcast the tx and register checktx callback
  159. checkTxResCh := make(chan *abci.Response, 1)
  160. err = mempool.CheckTx(tx, func(res *abci.Response) {
  161. checkTxResCh <- res
  162. })
  163. if err != nil {
  164. logger.Error("Error on broadcastTxCommit", "err", err)
  165. return nil, fmt.Errorf("Error on broadcastTxCommit: %v", err)
  166. }
  167. checkTxRes := <-checkTxResCh
  168. checkTxR := checkTxRes.GetCheckTx()
  169. if checkTxR.Code != abci.CodeTypeOK {
  170. // CheckTx failed!
  171. return &ctypes.ResultBroadcastTxCommit{
  172. CheckTx: *checkTxR,
  173. DeliverTx: abci.ResponseDeliverTx{},
  174. Hash: tx.Hash(),
  175. }, nil
  176. }
  177. // Wait for the tx to be included in a block,
  178. // timeout after something reasonable.
  179. // TODO: configurable?
  180. timer := time.NewTimer(60 * 2 * time.Second)
  181. select {
  182. case deliverTxResMsg := <-deliverTxResCh:
  183. deliverTxRes := deliverTxResMsg.(types.TMEventData).Unwrap().(types.EventDataTx)
  184. // The tx was included in a block.
  185. deliverTxR := deliverTxRes.Result
  186. logger.Info("DeliverTx passed ", "tx", data.Bytes(tx), "response", deliverTxR)
  187. return &ctypes.ResultBroadcastTxCommit{
  188. CheckTx: *checkTxR,
  189. DeliverTx: deliverTxR,
  190. Hash: tx.Hash(),
  191. Height: deliverTxRes.Height,
  192. }, nil
  193. case <-timer.C:
  194. logger.Error("failed to include tx")
  195. return &ctypes.ResultBroadcastTxCommit{
  196. CheckTx: *checkTxR,
  197. DeliverTx: abci.ResponseDeliverTx{},
  198. Hash: tx.Hash(),
  199. }, fmt.Errorf("Timed out waiting for transaction to be included in a block")
  200. }
  201. }
  202. // Get unconfirmed transactions including their number.
  203. //
  204. // ```shell
  205. // curl 'localhost:46657/unconfirmed_txs'
  206. // ```
  207. //
  208. // ```go
  209. // client := client.NewHTTP("tcp://0.0.0.0:46657", "/websocket")
  210. // result, err := client.UnconfirmedTxs()
  211. // ```
  212. //
  213. // > The above command returns JSON structured like this:
  214. //
  215. // ```json
  216. // {
  217. // "error": "",
  218. // "result": {
  219. // "txs": [],
  220. // "n_txs": 0
  221. // },
  222. // "id": "",
  223. // "jsonrpc": "2.0"
  224. // }
  225. // ```
  226. func UnconfirmedTxs() (*ctypes.ResultUnconfirmedTxs, error) {
  227. txs := mempool.Reap(-1)
  228. return &ctypes.ResultUnconfirmedTxs{len(txs), txs}, nil
  229. }
  230. // Get number of unconfirmed transactions.
  231. //
  232. // ```shell
  233. // curl 'localhost:46657/num_unconfirmed_txs'
  234. // ```
  235. //
  236. // ```go
  237. // client := client.NewHTTP("tcp://0.0.0.0:46657", "/websocket")
  238. // result, err := client.UnconfirmedTxs()
  239. // ```
  240. //
  241. // > The above command returns JSON structured like this:
  242. //
  243. // ```json
  244. // {
  245. // "error": "",
  246. // "result": {
  247. // "txs": null,
  248. // "n_txs": 0
  249. // },
  250. // "id": "",
  251. // "jsonrpc": "2.0"
  252. // }
  253. // ```
  254. func NumUnconfirmedTxs() (*ctypes.ResultUnconfirmedTxs, error) {
  255. return &ctypes.ResultUnconfirmedTxs{N: mempool.Size()}, nil
  256. }