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.

88 lines
1.6 KiB

  1. package main
  2. import (
  3. "crypto/rand"
  4. "encoding/binary"
  5. "encoding/hex"
  6. "fmt"
  7. "sync"
  8. "time"
  9. "github.com/pkg/errors"
  10. rpcclient "github.com/tendermint/go-rpc/client"
  11. rpctypes "github.com/tendermint/go-rpc/types"
  12. )
  13. type transacter struct {
  14. Target string
  15. Rate int
  16. wsc *rpcclient.WSClient
  17. stopped bool
  18. wg sync.WaitGroup
  19. }
  20. func newTransacter(target string, rate int) *transacter {
  21. return &transacter{
  22. Target: target,
  23. Rate: rate,
  24. wsc: rpcclient.NewWSClient(target, "/websocket"),
  25. }
  26. }
  27. func (t *transacter) Start() error {
  28. t.stopped = false
  29. if _, err := t.wsc.Start(); err != nil {
  30. return err
  31. }
  32. t.wg.Add(1)
  33. go t.sendLoop()
  34. return nil
  35. }
  36. func (t *transacter) Stop() {
  37. t.stopped = true
  38. t.wg.Wait()
  39. t.wsc.Stop()
  40. }
  41. func (t *transacter) sendLoop() {
  42. var num = 0
  43. for {
  44. startTime := time.Now()
  45. for i := 0; i < t.Rate; i++ {
  46. tx := generateTx(num)
  47. err := t.wsc.WriteJSON(rpctypes.RPCRequest{
  48. JSONRPC: "2.0",
  49. ID: "",
  50. Method: "broadcast_tx_async",
  51. Params: []interface{}{hex.EncodeToString(tx)},
  52. })
  53. if err != nil {
  54. panic(errors.Wrap(err, fmt.Sprintf("lost connection to %s", t.Target)))
  55. }
  56. num++
  57. }
  58. if t.stopped {
  59. t.wg.Done()
  60. return
  61. }
  62. timeToSend := time.Now().Sub(startTime)
  63. time.Sleep(time.Second - timeToSend)
  64. }
  65. }
  66. // generateTx returns a random byte sequence where first 8 bytes are the number
  67. // of transaction.
  68. func generateTx(num int) []byte {
  69. tx := make([]byte, 250)
  70. binary.PutUvarint(tx[:32], uint64(num))
  71. if _, err := rand.Read(tx[234:]); err != nil {
  72. panic(errors.Wrap(err, "err reading from crypto/rand"))
  73. }
  74. return tx
  75. }