forked from base/transaction-latency
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
298 lines (246 loc) · 8.25 KB
/
Copy pathmain.go
File metadata and controls
298 lines (246 loc) · 8.25 KB
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
292
293
294
295
296
297
298
package main
import (
"context"
"crypto/ecdsa"
"encoding/csv"
"encoding/hex"
"fmt"
"log"
"math/big"
"math/rand"
"os"
"strconv"
"time"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/joho/godotenv"
)
type stats struct {
SentAt time.Time
TxnHash string
IncludedInBlock uint64
InclusionDelay time.Duration
}
func main() {
err := godotenv.Load()
if err != nil {
log.Println("Error loading .env file")
}
region := os.Getenv("REGION")
if region == "" {
log.Fatal("REGION environment variable not set")
}
key := os.Getenv("PRIVATE_KEY")
if key == "" {
log.Fatal("PRIVATE_KEY environment variable not set")
}
toAddressRaw := os.Getenv("TO_ADDRESS")
if toAddressRaw == "" {
log.Fatal("TO_ADDRESS environment variable not set")
}
toAddress := common.HexToAddress(toAddressRaw)
if toAddress == (common.Address{}) {
log.Fatal("TO_ADDRESS environment variable not set")
}
endpoint1 := os.Getenv("BASE_NODE_ENDPOINT_1")
if endpoint1 == "" {
log.Fatal("BASE_NODE_ENDPOINT_1 environment variable not set")
}
endpoint2 := os.Getenv("BASE_NODE_ENDPOINT_2")
if endpoint2 == "" {
log.Fatal("BASE_NODE_ENDPOINT_2 environment variable not set")
}
sendTxnSync := os.Getenv("SEND_TXN_SYNC") == "true"
runEndpoint2Testing := os.Getenv("RUN_ENDPOINT2_TESTING") != "false"
pollingIntervalMs := 50
if pollingEnv := os.Getenv("POLLING_INTERVAL_MS"); pollingEnv != "" {
if parsed, err := strconv.Atoi(pollingEnv); err == nil {
pollingIntervalMs = parsed
}
}
log.Println("Polling interval ms", pollingIntervalMs)
numberOfTransactions := 100
if txnCountEnv := os.Getenv("NUMBER_OF_TRANSACTIONS"); txnCountEnv != "" {
if parsed, err := strconv.Atoi(txnCountEnv); err == nil {
numberOfTransactions = parsed
}
}
endpoint1Client, err := ethclient.Dial(endpoint1)
if err != nil {
log.Fatalf("Failed to connect to the Ethereum client: %v", err)
}
endpoint2Client, err := ethclient.Dial(endpoint2)
if err != nil {
log.Fatalf("Failed to connect to the Ethereum client: %v", err)
}
privateKey, err := crypto.HexToECDSA(key)
if err != nil {
log.Fatalf("Failed to load private key: %v", err)
}
publicKey := privateKey.Public()
publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
if !ok {
log.Fatal("Failed to cast public key to ECDSA")
}
fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)
var endpoint1Timings []stats
var endpoint2Timings []stats
chainId, err := endpoint2Client.NetworkID(context.Background())
if err != nil {
log.Fatalf("Failed to get network ID: %v", err)
}
endpoint1Errors := 0
endpoint2Errors := 0
log.Printf("Starting endpoint1 transactions, syncMode=%v", sendTxnSync)
for i := 0; i < numberOfTransactions; i++ {
timing, err := timeTransaction(chainId, privateKey, fromAddress, toAddress, endpoint1Client, sendTxnSync, pollingIntervalMs)
if err != nil {
endpoint1Errors += 1
log.Printf("Failed to send transaction: %v", err)
}
endpoint1Timings = append(endpoint1Timings, timing)
if !sendTxnSync {
// wait for it to be mined -- sleep a random amount between 600ms and 1s
time.Sleep(time.Duration(rand.Int63n(600)+600) * time.Millisecond)
} else {
time.Sleep(time.Duration(rand.Int63n(200)+200) * time.Millisecond)
}
}
// wait for the final endpoint1 transaction to land
time.Sleep(5 * time.Second)
if runEndpoint2Testing {
log.Printf("Starting endpoint2 transactions, syncMode=%v", sendTxnSync)
for i := 0; i < numberOfTransactions; i++ {
// Use the same mode as endpoint1 for fair comparison
timing, err := timeTransaction(chainId, privateKey, fromAddress, toAddress, endpoint2Client, sendTxnSync, pollingIntervalMs)
if err != nil {
endpoint2Errors += 1
log.Printf("Failed to send transaction: %v", err)
}
endpoint2Timings = append(endpoint2Timings, timing)
// wait for it to be mined -- sleep a random amount between 4s and 3s
time.Sleep(time.Duration(rand.Int63n(1000)+4000) * time.Millisecond)
}
} else {
log.Printf("Skipping endpoint2 transactions (RUN_ENDPOINT2_TESTING=false)")
}
if err := writeToFile(fmt.Sprintf("/data/endpoint1-%s.csv", region), endpoint1Timings); err != nil {
log.Fatalf("Failed to write to file: %v", err)
}
if runEndpoint2Testing {
if err := writeToFile(fmt.Sprintf("/data/endpoint2-%s.csv", region), endpoint2Timings); err != nil {
log.Fatalf("Failed to write to file: %v", err)
}
}
log.Printf("Completed test with %d transactions", numberOfTransactions)
log.Printf("Endpoint1 errors: %v", endpoint1Errors)
log.Printf("Endpoint2 errors: %v", endpoint2Errors)
}
func writeToFile(filename string, data []stats) error {
file, err := os.Create(filename)
if err != nil {
log.Fatalf("Failed to create file: %v", err)
}
defer file.Close()
writer := csv.NewWriter(file)
defer writer.Flush()
header := []string{"sent_at", "txn_hash", "included_in_block", "inclusion_delay_ms"}
if err := writer.Write(header); err != nil {
log.Fatalf("Failed to write to file: %v", err)
}
for _, d := range data {
row := []string{
d.SentAt.String(),
d.TxnHash,
strconv.FormatUint(d.IncludedInBlock, 10),
strconv.FormatInt(d.InclusionDelay.Milliseconds(), 10),
}
if err := writer.Write(row); err != nil {
log.Fatalf("Failed to write to file: %v", err)
}
}
return nil
}
func timeTransaction(chainId *big.Int, privateKey *ecdsa.PrivateKey, fromAddress common.Address, toAddress common.Address, client *ethclient.Client, useSyncRPC bool, pollingIntervalMs int) (stats, error) {
nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
if err != nil {
return stats{}, fmt.Errorf("unable to get nonce: %v", err)
}
gasPrice, err := client.SuggestGasPrice(context.Background())
if err != nil {
return stats{}, fmt.Errorf("unable to get gas price: %v", err)
}
gasLimit := uint64(21000)
value := big.NewInt(100)
tip, err := client.SuggestGasTipCap(context.Background())
if err != nil {
return stats{}, fmt.Errorf("unable to get gas price: %v", err)
}
tx := types.NewTx(&types.DynamicFeeTx{
ChainID: chainId,
Nonce: nonce,
GasTipCap: tip,
GasFeeCap: gasPrice,
Gas: gasLimit,
To: &toAddress,
Value: value,
Data: nil,
})
signedTx, err := types.SignTx(tx, types.NewPragueSigner(chainId), privateKey)
if err != nil {
return stats{}, fmt.Errorf("unable to sign transaction: %v", err)
}
if useSyncRPC {
return sendTransactionSync(client, signedTx)
}
return sendTransactionAsync(client, signedTx, pollingIntervalMs)
}
func sendTransactionSync(client *ethclient.Client, signedTx *types.Transaction) (stats, error) {
rawTx, err := signedTx.MarshalBinary()
if err != nil {
return stats{}, fmt.Errorf("unable to marshal transaction: %v", err)
}
txnData := "0x" + hex.EncodeToString(rawTx)
sentAt := time.Now()
var receipt *types.Receipt
err = client.Client().CallContext(context.Background(), &receipt, "eth_sendRawTransactionSync", txnData)
if err != nil {
return stats{}, fmt.Errorf("unable to send sync transaction: %v", err)
}
if receipt == nil {
return stats{}, fmt.Errorf("unable to send sync transaction: receipt not found")
}
log.Println("Transaction sent sync: ", signedTx.Hash().Hex())
now := time.Now()
return stats{
SentAt: sentAt,
InclusionDelay: now.Sub(sentAt),
TxnHash: signedTx.Hash().Hex(),
IncludedInBlock: receipt.BlockNumber.Uint64(),
}, nil
}
func sendTransactionAsync(client *ethclient.Client, signedTx *types.Transaction, pollingIntervalMs int) (stats, error) {
sentAt := time.Now()
err := client.SendTransaction(context.Background(), signedTx)
if err != nil {
return stats{}, fmt.Errorf("unable to send transaction: %v", err)
}
log.Println("Transaction sent async: ", signedTx.Hash().Hex())
for i := 0; i < 1000; i++ {
receipt, err := client.TransactionReceipt(context.Background(), signedTx.Hash())
if err != nil {
time.Sleep(time.Duration(pollingIntervalMs) * time.Millisecond)
} else {
now := time.Now()
return stats{
SentAt: sentAt,
InclusionDelay: now.Sub(sentAt),
TxnHash: signedTx.Hash().Hex(),
IncludedInBlock: receipt.BlockNumber.Uint64(),
}, nil
}
}
return stats{}, fmt.Errorf("failed to get transaction")
}