Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
404 lines (351 loc) · 13.6 KB
/
Copy pathmain.go
File metadata and controls
404 lines (351 loc) · 13.6 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
package main
import (
"bytes"
"context"
"encoding/json"
"io"
"log"
"net/http"
"time"
"github.com/BlockRazorinc/base-api-client-go/basepb"
"github.com/andybalholm/brotli"
"github.com/ethereum/go-ethereum/core/types"
"github.com/gorilla/websocket"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/metadata"
"google.golang.org/protobuf/encoding/protojson"
)
const (
// Replace with the server address geographically closest to you for optimal performance.
grpcAddr = "tokyo.grpc.base.blockrazor.xyz:80"
websocketAddr = "ws://tokyo.base.blockrazor.xyz:81/ws"
//websocketAddr = "ws://frankfurt.base.blockrazor.xyz:81/ws"
//websocketAddr = "ws://virginia.base.blockrazor.xyz:81/ws"
authToken = "your token goes here" // Replace with your authentication token.
)
func main() {
// main is the entry point of the program.
// It directly calls one of the stream functions to demonstrate its usage.
// The program will exit once the called function completes.
// GetFlashBlockStream(authToken)
// GetFlashTransactionStream(authToken)
GetBlockStream(authToken)
// GetWebSocketFlashBlockStream(authToken)
// GetWebSocketFlashTransactionStream(authToken)
// sendTransactions(client, authToken, "0x + ....") // It's recommended to keep the gRPC client alive for sending transactions.
}
func GetFlashTransactionStream(authToken string) {
log.Printf("[FlashTransactionStream] Attempting to connect to gRPC server at %s...", grpcAddr)
// Establish a connection to the gRPC server with a timeout.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
conn, err := grpc.DialContext(ctx, grpcAddr,
grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Printf("[FlashTransactionStream] Failed to connect to gRPC server: %v", err)
return
}
defer conn.Close()
log.Println("[FlashTransactionStream] Successfully connected to gRPC server.")
client := basepb.NewBaseApiClient(conn)
// Create a new context with authentication metadata for the stream subscription.
streamCtx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs("authorization", authToken))
stream, err := client.GetNewFlashblockTransactionsStream(streamCtx, &basepb.GetNewFlashblockTransactionsStreamRequest{})
if err != nil {
log.Printf("[FlashTransactionStream] Failed to subscribe to stream: %v", err)
return
}
log.Println("[FlashTransactionStream] Subscription successful. Waiting for new txs...")
// Loop indefinitely to receive messages from the stream.
for {
tx, err := stream.Recv()
if err != nil {
if err == io.EOF {
log.Println("[FlashTransactionStream] Stream closed by the server (EOF).")
} else {
log.Printf("[FlashTransactionStream] An error occurred while receiving data: %v", err)
}
break
}
log.Printf("=> [FlashTransactionStream] Received new tx: BlockNumber=%s, txHash=%s, TransactionIndex=%s",
tx.GetBlockNumber(),
tx.GetHash(),
tx.GetTransactionIndex(),
)
}
}
// GetBlockStream provides a simplified example of subscribing to and processing the regular block stream.
// Note: This function attempts to connect and subscribe only once. For production use, implement your own reconnection logic.
func GetBlockStream(authToken string) {
log.Printf("[BlockStream] Attempting to connect to gRPC server at %s...", grpcAddr)
// Establish a connection to the gRPC server with a timeout.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
conn, err := grpc.DialContext(ctx, grpcAddr,
grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Printf("[BlockStream] Failed to connect to gRPC server: %v", err)
return
}
defer conn.Close()
log.Println("[BlockStream] Successfully connected to gRPC server.")
client := basepb.NewBaseApiClient(conn)
// Create a new context with authentication metadata for the stream subscription.
streamCtx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs("authorization", authToken))
stream, err := client.GetBlockStream(streamCtx, &basepb.GetBlockStreamRequest{})
if err != nil {
log.Printf("[BlockStream] Failed to subscribe to stream: %v", err)
return
}
log.Println("[BlockStream] Subscription successful. Waiting for new blocks...")
// Loop indefinitely to receive messages from the stream.
for {
block, err := stream.Recv()
if err != nil {
if err == io.EOF {
log.Println("[BlockStream] Stream closed by the server (EOF).")
} else {
log.Printf("[BlockStream] An error occurred while receiving data: %v", err)
}
break // Exit the loop on error or stream closure.
}
// Process the received block data.
log.Printf("=> [BlockStream] Received new block: Number=%d, Hash=%s, TransactionCount=%d",
block.GetBlockNumber(),
block.GetBlockHash(),
len(block.GetTransactions()),
)
// To decode transactions, you can call DecodeTransactions(block.Transactions).
}
}
// GetFlashBlockStream provides a simplified example of subscribing to and processing the flash block stream.
// Note: This function attempts to connect and subscribe only once. For production use, implement your own reconnection logic.
func GetFlashBlockStream(authToken string) {
log.Printf("[FlashStream] Attempting to connect to gRPC server at %s...", grpcAddr)
// Establish a connection to the gRPC server with a timeout.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
conn, err := grpc.DialContext(ctx, grpcAddr,
grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Printf("[FlashStream] Failed to connect to gRPC server: %v", err)
return
}
defer conn.Close()
log.Println("[FlashStream] Successfully connected to gRPC server.")
client := basepb.NewBaseApiClient(conn)
// Create a new context with authentication metadata for the stream subscription.
streamCtx := metadata.NewOutgoingContext(context.Background(), metadata.Pairs("authorization", authToken))
stream, err := client.GetRawFlashBlockStream(streamCtx, &basepb.GetRawFlashBlocksStreamRequest{})
if err != nil {
log.Printf("[FlashStream] Failed to subscribe to stream: %v", err)
return
}
log.Println("[FlashStream] Subscription successful. Waiting for new flash blocks...")
// Loop indefinitely to receive messages from the stream.
for {
block, err := stream.Recv()
if err != nil {
if err == io.EOF {
log.Println("[FlashStream] Stream closed by the server (EOF).")
} else {
log.Printf("[FlashStream] An error occurred while receiving data: %v", err)
}
break // Exit the loop on error or stream closure.
}
// Process the received flash block data.
jsonString, err := ParseFlashBlockByte(block.Message)
if err != nil {
log.Printf("[FlashStream] Failed to parse flash block data: %v", err)
continue
}
var jsonMap map[string]interface{}
if err := json.Unmarshal([]byte(jsonString), &jsonMap); err != nil {
log.Printf("[FlashStream] Failed to unmarshal flash block JSON: %v", err)
continue
}
printPretty(jsonMap)
}
}
// sendTransactions is an example function for sending a transaction.
// It's designed to reuse an existing gRPC client connection to avoid connection latency.
func sendTransactions(client basepb.BaseApiClient, authToken string, rawTxString string) {
log.Println("[SendTx] Sending transaction...")
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// Add the authentication token to the outgoing request's metadata.
md := metadata.Pairs("authorization", authToken)
ctx = metadata.NewOutgoingContext(ctx, md)
req := &basepb.SendTransactionRequest{
RawTransaction: rawTxString,
}
res, err := client.SendTransaction(ctx, req)
if err != nil {
log.Printf("[SendTx] Failed to send transaction: %v", err)
} else {
log.Printf("[SendTx] Transaction sent successfully. Hash: %s", res.GetTxHash())
}
}
// FlashBlockWebSocketResponse defines the outer JSON-RPC structure for WebSocket messages.
type FlashBlockWebSocketResponse struct {
JsonRPC string `json:"jsonrpc"`
Result []byte `json:"result"`
}
// GetWebSocketFlashBlockStream provides a simplified example of using the WebSocket API to subscribe to the flash block stream.
// Note: This function attempts to connect only once and will exit on a read error. For production use, implement your own reconnection logic.
func GetWebSocketFlashBlockStream(authToken string) {
// Set up the HTTP header with the authorization token.
header := http.Header{}
header.Set("Authorization", authToken)
// Dial the WebSocket server.
dialer := websocket.DefaultDialer
conn, resp, err := dialer.Dial(websocketAddr, header)
if err != nil {
if resp != nil {
log.Fatalf("[WebSocket] Dial failed: %v (HTTP status: %s)", err, resp.Status)
}
log.Fatalf("[WebSocket] Dial failed: %v", err)
}
defer conn.Close()
log.Printf("[WebSocket] Successfully connected to %s", websocketAddr)
// Prepare the JSON-RPC subscription request.
req := map[string]interface{}{
"jsonrpc": "2.0",
"method": "subscribe_FlashBlock",
"params": []interface{}{},
"id": 1,
}
reqB, _ := json.Marshal(req)
if err := conn.WriteMessage(websocket.TextMessage, reqB); err != nil {
log.Fatalf("[WebSocket] Failed to send subscription request: %v", err)
}
log.Printf("[WebSocket] Subscription request sent: %s", string(reqB))
// Loop indefinitely to read messages from the server.
for {
msgType, msg, err := conn.ReadMessage()
if err != nil {
log.Printf("[WebSocket] Error reading message: %v", err)
return // Exit the function on any read error.
}
if msgType != websocket.TextMessage && msgType != websocket.BinaryMessage {
continue // Ignore messages that are not text or binary.
}
// Parse the outer JSON-RPC response wrapper.
var outer = &FlashBlockWebSocketResponse{}
if err := json.Unmarshal(msg, &outer); err != nil {
log.Printf("[WebSocket] Failed to parse JSON from server: %v\nRaw data: %s", err, string(msg))
continue
}
// Extract the "result" field, which contains the actual flash block data, and process it.
resultRaw := outer.Result
if jsonString, err := ParseFlashBlockByte(resultRaw); err == nil {
printPretty(jsonString)
} else {
log.Printf("[WebSocket] Received message without a valid result field. Raw data: %s", string(msg))
}
}
}
// --- Utility Functions ---
// ParseFlashBlockByte decompresses the brotli-compressed binary data of a flash block.
func ParseFlashBlockByte(data []byte) (string, error) {
br := brotli.NewReader(bytes.NewReader(data))
var buf bytes.Buffer
_, err := buf.ReadFrom(br)
if err != nil {
return "", err
}
return buf.String(), nil
}
// DecodeTransactions decodes a slice of byte slices into go-ethereum Transaction objects.
func DecodeTransactions(txData [][]byte) ([]*types.Transaction, error) {
transactions := make([]*types.Transaction, len(txData))
for idx, txByte := range txData {
tx := &types.Transaction{}
err := tx.UnmarshalBinary(txByte)
if err != nil {
log.Printf("[DecodeTx] Error unmarshalling transaction binary: %v", err)
return nil, err
}
log.Printf("[DecodeTx] Decoded transaction with hash: %v", tx.Hash())
transactions[idx] = tx
}
return transactions, nil
}
// printPretty formats and prints a JSON string or any interface with indentation for readability.
func printPretty(v interface{}) {
var out []byte
var err error
// If the input is already a string, attempt to unmarshal and re-marshal it for formatting.
if s, ok := v.(string); ok {
var js map[string]interface{}
if json.Unmarshal([]byte(s), &js) == nil {
out, err = json.MarshalIndent(js, "", " ")
} else {
// If it's a string but not valid JSON, just print it directly.
out = []byte(s)
}
} else {
// If it's not a string, marshal it directly.
out, err = json.MarshalIndent(v, "", " ")
}
if err != nil {
log.Printf("Failed to marshal for pretty printing, printing raw value: %#v\n", v)
return
}
log.Println(string(out))
}
type FlashTransactionWebSocketResponse struct {
JsonRPC string `json:"jsonrpc"`
Result *basepb.NewFlashblockTransaction `json:"result"`
}
func GetWebSocketFlashTransactionStream(authToken string) {
header := http.Header{}
header.Set("Authorization", authToken)
// Dial the WebSocket server.
dialer := websocket.DefaultDialer
conn, resp, err := dialer.Dial(websocketAddr, header)
if err != nil {
if resp != nil {
log.Fatalf("[WebSocket] Dial failed: %v (HTTP status: %s)", err, resp.Status)
}
log.Fatalf("[WebSocket] Dial failed: %v", err)
}
defer conn.Close()
log.Printf("[WebSocket] Successfully connected to %s", websocketAddr)
// Prepare the JSON-RPC subscription request.
req := map[string]interface{}{
"jsonrpc": "2.0",
"method": "subscribe_FlashTransaction",
"params": []interface{}{},
"id": 1,
}
reqB, _ := json.Marshal(req)
if err := conn.WriteMessage(websocket.TextMessage, reqB); err != nil {
log.Fatalf("[WebSocket] Failed to send subscription request: %v", err)
}
log.Printf("[WebSocket] Subscription request sent: %s", string(reqB))
for {
_, msg, err := conn.ReadMessage()
if err != nil {
log.Printf("[WebSocket] read error: %v", err)
return
}
var outer FlashTransactionWebSocketResponse
if err := json.Unmarshal(msg, &outer); err != nil {
log.Printf("[WebSocket] unmarshal outer message failed: %v, raw=%s", err, string(msg))
continue
}
if outer.Result == nil {
log.Printf("[WebSocket] Received message without a valid result field. Raw data: %s", string(msg))
continue
}
tx := outer.Result
b, err := protojson.Marshal(tx)
if err != nil {
continue
}
jsonString := string(b)
printPretty(jsonString)
}
}