forked from sei-protocol/sei-chain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loadtest_client.go
291 lines (258 loc) · 8.59 KB
/
loadtest_client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
"github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
typestx "github.com/cosmos/cosmos-sdk/types/tx"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"crypto/tls"
"github.com/k0kubun/pp/v3"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
type LoadTestClient struct {
LoadTestConfig Config
TestConfig EncodingConfig
TxClient typestx.ServiceClient
TxHashFile *os.File
SignerClient *SignerClient
ChainID string
TxHashList []string
TxResponseChan chan *string
TxHashListMutex *sync.Mutex
GrpcConn *grpc.ClientConn
StakingQueryClient stakingtypes.QueryClient
// Staking specific variables
Validators []stakingtypes.Validator
// DelegationMap is a map of delegator -> validator -> delegated amount
DelegationMap map[string]map[string]int
// Tokenfactory specific variables
TokenFactoryDenomOwner map[string]string
// Only one admin message can go in per block
generatedAdminMessageForBlock bool
// Messages that has to be sent from the admin account
isAdminMessageMapping map[string]bool
}
func NewLoadTestClient(config Config) *LoadTestClient {
var dialOptions []grpc.DialOption
// NOTE: Will likely need to whitelist node from elb rate limits - add ip to producer ip set
if config.TLS {
dialOptions = append(dialOptions, grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{InsecureSkipVerify: true}))) //nolint:gosec // Use insecure skip verify.
} else {
dialOptions = append(dialOptions, grpc.WithInsecure())
}
grpcConn, _ := grpc.Dial(
config.GrpcEndpoint,
dialOptions...,
)
TxClient := typestx.NewServiceClient(grpcConn)
// setup output files
userHomeDir, _ := os.UserHomeDir()
_ = os.Mkdir(filepath.Join(userHomeDir, "outputs"), os.ModePerm)
filename := filepath.Join(userHomeDir, "outputs", "test_tx_hash")
_ = os.Remove(filename)
outputFile, _ := os.OpenFile(filename, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644)
return &LoadTestClient{
LoadTestConfig: config,
TestConfig: TestConfig,
TxClient: TxClient,
TxHashFile: outputFile,
SignerClient: NewSignerClient(config.NodeURI),
ChainID: config.ChainID,
TxHashList: []string{},
TxResponseChan: make(chan *string),
TxHashListMutex: &sync.Mutex{},
GrpcConn: grpcConn,
StakingQueryClient: stakingtypes.NewQueryClient(grpcConn),
DelegationMap: map[string]map[string]int{},
TokenFactoryDenomOwner: map[string]string{},
generatedAdminMessageForBlock: false,
isAdminMessageMapping: map[string]bool{CollectRewards: true, DistributeRewards: true},
}
}
func (c *LoadTestClient) SetValidators() {
if strings.Contains(c.LoadTestConfig.MessageType, "staking") {
if resp, err := c.StakingQueryClient.Validators(context.Background(), &stakingtypes.QueryValidatorsRequest{}); err != nil {
panic(err)
} else {
c.Validators = resp.Validators
}
}
}
func (c *LoadTestClient) Close() {
c.GrpcConn.Close()
}
func (c *LoadTestClient) AppendTxHash(txHash string) {
c.TxResponseChan <- &txHash
}
func (c *LoadTestClient) WriteTxHashToFile() {
fmt.Printf("Writing Tx Hashes to: %s \n", c.TxHashFile.Name())
file := c.TxHashFile
for _, txHash := range c.TxHashList {
txHashLine := fmt.Sprintf("%s\n", txHash)
if _, err := file.WriteString(txHashLine); err != nil {
panic(err)
}
}
}
func (c *LoadTestClient) BuildTxs() (workgroups []*sync.WaitGroup, sendersList [][]func()) {
config := c.LoadTestConfig
numberOfAccounts := config.TxsPerBlock / config.MsgsPerTx * 2 // * 2 because we need two sets of accounts
activeAccounts := []int{}
inactiveAccounts := []int{}
for i := 0; i < int(numberOfAccounts); i++ {
if i%2 == 0 {
activeAccounts = append(activeAccounts, i)
} else {
inactiveAccounts = append(inactiveAccounts, i)
}
}
valKeys := c.SignerClient.GetValKeys()
for i := 0; i < int(config.Rounds); i++ {
fmt.Printf("Preparing %d-th round\n", i)
wg := &sync.WaitGroup{}
var senders []func()
workgroups = append(workgroups, wg)
c.generatedAdminMessageForBlock = false
for j, account := range activeAccounts {
accountIdentifier := fmt.Sprint(account)
accountKeyPath := c.SignerClient.GetTestAccountKeyPath(uint64(account))
key := c.SignerClient.GetKey(accountIdentifier, "test", accountKeyPath)
msgs, failureExpected, signer, gas, fee := c.generateMessage(config, key, config.MsgsPerTx)
txBuilder := TestConfig.TxConfig.NewTxBuilder()
_ = txBuilder.SetMsgs(msgs...)
seqDelta := uint64(i / 2)
mode := typestx.BroadcastMode_BROADCAST_MODE_SYNC
if j == len(activeAccounts)-1 {
mode = typestx.BroadcastMode_BROADCAST_MODE_BLOCK
}
// Note: There is a potential race condition here with seqnos
// in which a later seqno is delievered before an earlier seqno
// In practice, we haven't run into this issue so we'll leave this
// as is.
sender := SendTx(signer, &txBuilder, mode, seqDelta, failureExpected, *c, gas, fee)
wg.Add(1)
senders = append(senders, func() {
defer wg.Done()
sender()
})
}
senders = append(senders, c.GenerateOracleSenders(i, config, valKeys, wg)...)
sendersList = append(sendersList, senders)
inactiveAccounts, activeAccounts = activeAccounts, inactiveAccounts
}
return workgroups, sendersList
}
func (c *LoadTestClient) GenerateOracleSenders(i int, config Config, valKeys []cryptotypes.PrivKey, waitGroup *sync.WaitGroup) []func() {
senders := []func(){}
if config.RunOracle && i%2 == 0 {
for _, valKey := range valKeys {
// generate oracle tx
msg := generateOracleMessage(valKey)
txBuilder := TestConfig.TxConfig.NewTxBuilder()
_ = txBuilder.SetMsgs(msg)
seqDelta := uint64(i / 2)
mode := typestx.BroadcastMode_BROADCAST_MODE_SYNC
sender := SendTx(valKey, &txBuilder, mode, seqDelta, false, *c, 30000, 100000)
waitGroup.Add(1)
senders = append(senders, func() {
defer waitGroup.Done()
sender()
})
}
}
return senders
}
func (c *LoadTestClient) SendTxs(workgroups []*sync.WaitGroup, sendersList [][]func()) {
defer close(c.TxResponseChan)
lastHeight := getLastHeight(c.LoadTestConfig.BlockchainEndpoint)
for i := 0; i < int(c.LoadTestConfig.Rounds); i++ {
newHeight := getLastHeight(c.LoadTestConfig.BlockchainEndpoint)
for newHeight == lastHeight {
time.Sleep(10 * time.Millisecond)
newHeight = getLastHeight(c.LoadTestConfig.BlockchainEndpoint)
}
fmt.Printf("Sending %d-th block\n", i)
senders := sendersList[i]
wg := workgroups[i]
for _, sender := range senders {
go sender()
}
wg.Wait()
lastHeight = newHeight
}
}
func (c *LoadTestClient) GatherTxHashes() {
for txHash := range c.TxResponseChan {
c.TxHashList = append(c.TxHashList, *txHash)
}
fmt.Printf("Transactions Sent=%d\n", len(c.TxHashList))
}
func (c *LoadTestClient) ValidateTxs() {
defer c.Close()
numTxs := len(c.TxHashList)
resultChan := make(chan *types.TxResponse, numTxs)
var waitGroup sync.WaitGroup
if numTxs == 0 {
return
}
for _, txHash := range c.TxHashList {
waitGroup.Add(1)
go func(txHash string) {
defer waitGroup.Done()
resultChan <- c.GetTxResponse(txHash)
}(txHash)
}
go func() {
waitGroup.Wait()
close(resultChan)
}()
fmt.Printf("Validating %d Transactions... \n", len(c.TxHashList))
waitGroup.Wait()
notCommittedTxs := 0
responseCodeMap := map[int]int{}
responseStringMap := map[string]int{}
for result := range resultChan {
// If the result is nil then that means the transaction was not committed
if result == nil {
notCommittedTxs++
continue
}
code := result.Code
codeString := "ok"
if code != 0 {
codespace := result.Codespace
error := sdkerrors.ABCIError(codespace, code, fmt.Sprintf("Error code=%d ", code))
codeString = error.Error()
}
responseStringMap[codeString]++
responseCodeMap[int(code)]++
}
fmt.Printf("Transactions not committed: %d\n", notCommittedTxs)
pp.Printf("Response Code Mapping: \n %s \n", responseStringMap)
IncrTxNotCommitted(notCommittedTxs)
for reason, count := range responseStringMap {
IncrTxProcessCode(reason, count)
}
}
func (c *LoadTestClient) GetTxResponse(hash string) *types.TxResponse {
grpcRes, err := c.TxClient.GetTx(
context.Background(),
&typestx.GetTxRequest{
Hash: hash,
},
)
fmt.Printf("Validated: %s\n", hash)
if err != nil {
fmt.Println(err)
return nil
}
return grpcRes.TxResponse
}