forked from 0xPolygonHermez/zkevm-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
query.go
403 lines (338 loc) · 10.1 KB
/
query.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
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
package jsonrpc
import (
"context"
"encoding/json"
"fmt"
"sync"
"time"
"github.com/0xPolygonHermez/zkevm-node/hex"
"github.com/0xPolygonHermez/zkevm-node/jsonrpc/types"
"github.com/0xPolygonHermez/zkevm-node/log"
"github.com/0xPolygonHermez/zkevm-node/state"
"github.com/ethereum/go-ethereum/common"
"github.com/gorilla/websocket"
"github.com/jackc/pgx/v4"
)
const (
// FilterTypeLog represents a filter of type log.
FilterTypeLog = "log"
// FilterTypeBlock represents a filter of type block.
FilterTypeBlock = "block"
// FilterTypePendingTx represent a filter of type pending Tx.
FilterTypePendingTx = "pendingTx"
)
// Filter represents a filter.
type Filter struct {
ID string
Type FilterType
Parameters interface{}
LastPoll time.Time
WsConn *concurrentWsConn
wsQueue *state.Queue[[]byte]
wsQueueSignal *sync.Cond
}
// EnqueueSubscriptionDataToBeSent enqueues subscription data to be sent
// via web sockets connection
func (f *Filter) EnqueueSubscriptionDataToBeSent(data []byte) {
f.wsQueue.Push(data)
f.wsQueueSignal.Broadcast()
}
// SendEnqueuedSubscriptionData consumes all the enqueued subscription data
// and sends it via web sockets connection.
func (f *Filter) SendEnqueuedSubscriptionData() {
for {
// wait for a signal that a new item was
// added to the queue
log.Debugf("waiting subscription data signal")
f.wsQueueSignal.L.Lock()
f.wsQueueSignal.Wait()
f.wsQueueSignal.L.Unlock()
log.Debugf("subscription data signal received, sending enqueued data")
for {
d, err := f.wsQueue.Pop()
if err == state.ErrQueueEmpty {
break
} else if err != nil {
log.Errorf("failed to pop subscription data from queue to be sent via web sockets to filter %v, %s", f.ID, err.Error())
break
}
f.sendSubscriptionResponse(d)
}
}
}
// sendSubscriptionResponse send data as subscription response via
// web sockets connection controlled by a mutex
func (f *Filter) sendSubscriptionResponse(data []byte) {
const errMessage = "Unable to write WS message to filter %v, %s"
start := time.Now()
res := types.SubscriptionResponse{
JSONRPC: "2.0",
Method: "eth_subscription",
Params: types.SubscriptionResponseParams{
Subscription: f.ID,
Result: data,
},
}
message, err := json.Marshal(res)
if err != nil {
log.Errorf(fmt.Sprintf(errMessage, f.ID, err.Error()))
return
}
err = f.WsConn.WriteMessage(websocket.TextMessage, message)
if err != nil {
log.Errorf(fmt.Sprintf(errMessage, f.ID, err.Error()))
return
}
log.Debugf("WS message sent: %v", string(message))
log.Debugf("[SendSubscriptionResponse] took %v", time.Since(start))
}
// FilterType express the type of the filter, block, logs, pending transactions
type FilterType string
// LogFilter is a filter for logs
type LogFilter struct {
BlockHash *common.Hash
FromBlock *types.BlockNumber
ToBlock *types.BlockNumber
Addresses []common.Address
Topics [][]common.Hash
Since *time.Time
}
// addTopic adds specific topics to the log filter topics
func (f *LogFilter) addTopic(topics ...string) error {
if f.Topics == nil {
f.Topics = [][]common.Hash{}
}
topicsHashes := []common.Hash{}
for _, topic := range topics {
topicHash := common.Hash{}
if err := topicHash.UnmarshalText([]byte(topic)); err != nil {
return err
}
topicsHashes = append(topicsHashes, topicHash)
}
f.Topics = append(f.Topics, topicsHashes)
return nil
}
// addAddress Adds the address to the log filter
func (f *LogFilter) addAddress(raw string) error {
if f.Addresses == nil {
f.Addresses = []common.Address{}
}
addr := common.Address{}
if err := addr.UnmarshalText([]byte(raw)); err != nil {
return err
}
f.Addresses = append(f.Addresses, addr)
return nil
}
// MarshalJSON allows to customize the JSON representation.
func (f *LogFilter) MarshalJSON() ([]byte, error) {
var obj types.LogFilterRequest
obj.BlockHash = f.BlockHash
if f.FromBlock != nil && (*f.FromBlock == types.LatestBlockNumber) {
fromBlock := ""
obj.FromBlock = &fromBlock
} else if f.FromBlock != nil {
fromBlock := hex.EncodeUint64(uint64(*f.FromBlock))
obj.FromBlock = &fromBlock
}
if f.ToBlock != nil && (*f.ToBlock == types.LatestBlockNumber) {
toBlock := ""
obj.ToBlock = &toBlock
} else if f.ToBlock != nil {
toBlock := hex.EncodeUint64(uint64(*f.ToBlock))
obj.ToBlock = &toBlock
}
if f.Addresses != nil {
if len(f.Addresses) == 1 {
obj.Address = f.Addresses[0].Hex()
} else {
obj.Address = f.Addresses
}
}
obj.Topics = make([]interface{}, 0, len(f.Topics))
for _, topic := range f.Topics {
if len(topic) == 0 {
obj.Topics = append(obj.Topics, nil)
} else if len(topic) == 1 {
obj.Topics = append(obj.Topics, topic[0])
} else {
obj.Topics = append(obj.Topics, topic)
}
}
return json.Marshal(obj)
}
// UnmarshalJSON decodes a json object
func (f *LogFilter) UnmarshalJSON(data []byte) error {
var obj types.LogFilterRequest
err := json.Unmarshal(data, &obj)
if err != nil {
return err
}
f.BlockHash = obj.BlockHash
lbb := types.LatestBlockNumber
if obj.FromBlock != nil && *obj.FromBlock == "" {
f.FromBlock = &lbb
} else if obj.FromBlock != nil {
bn, err := types.StringToBlockNumber(*obj.FromBlock)
if err != nil {
return err
}
f.FromBlock = &bn
}
if obj.ToBlock != nil && *obj.ToBlock == "" {
f.ToBlock = &lbb
} else if obj.ToBlock != nil {
bn, err := types.StringToBlockNumber(*obj.ToBlock)
if err != nil {
return err
}
f.ToBlock = &bn
}
if obj.Address != nil {
// decode address, either "" or [""]
switch raw := obj.Address.(type) {
case string:
// ""
if err := f.addAddress(raw); err != nil {
return err
}
case []interface{}:
// ["", ""]
for _, addr := range raw {
if item, ok := addr.(string); ok {
if err := f.addAddress(item); err != nil {
return err
}
} else {
return fmt.Errorf("address expected")
}
}
default:
return fmt.Errorf("failed to decode address. Expected either '' or ['', '']")
}
}
if obj.Topics != nil {
// decode topics, either "" or ["", ""] or null
for _, item := range obj.Topics {
switch raw := item.(type) {
case string:
// ""
if err := f.addTopic(raw); err != nil {
return err
}
case []interface{}:
// ["", ""]
res := []string{}
for _, i := range raw {
if item, ok := i.(string); ok {
res = append(res, item)
} else {
return fmt.Errorf("hash expected")
}
}
if err := f.addTopic(res...); err != nil {
return err
}
case nil:
// null
if err := f.addTopic(); err != nil {
return err
}
default:
return fmt.Errorf("failed to decode topics. Expected '' or [''] or null")
}
}
}
// decode topics
return nil
}
// Match returns whether the receipt includes topics for this filter
func (f *LogFilter) Match(log *types.Log) bool {
// check addresses
if len(f.Addresses) > 0 {
match := false
for _, addr := range f.Addresses {
if addr == log.Address {
match = true
}
}
if !match {
return false
}
}
// check topics
if len(f.Topics) > len(log.Topics) {
return false
}
for i, sub := range f.Topics {
match := len(sub) == 0
for _, topic := range sub {
if log.Topics[i] == topic {
match = true
break
}
}
if !match {
return false
}
}
return true
}
// GetNumericBlockNumbers load the numeric block numbers from state accordingly
// to the provided from and to block number
func (f *LogFilter) GetNumericBlockNumbers(ctx context.Context, cfg Config, s types.StateInterface, e types.EthermanInterface, dbTx pgx.Tx) (uint64, uint64, types.Error) {
return getNumericBlockNumbers(ctx, s, e, f.FromBlock, f.ToBlock, cfg.MaxLogsBlockRange, state.ErrMaxLogsBlockRangeLimitExceeded, dbTx)
}
// ShouldFilterByBlockHash if the filter should consider the block hash value
func (f *LogFilter) ShouldFilterByBlockHash() bool {
return f.BlockHash != nil
}
// ShouldFilterByBlockRange if the filter should consider the block range values
func (f *LogFilter) ShouldFilterByBlockRange() bool {
return f.FromBlock != nil || f.ToBlock != nil
}
// Validate check if the filter instance is valid
func (f *LogFilter) Validate() error {
if f.ShouldFilterByBlockHash() && f.ShouldFilterByBlockRange() {
return ErrFilterInvalidPayload
}
return nil
}
// NativeBlockHashBlockRangeFilter is a filter to filter native block hash by block by number
type NativeBlockHashBlockRangeFilter struct {
FromBlock types.BlockNumber `json:"fromBlock"`
ToBlock types.BlockNumber `json:"toBlock"`
}
// GetNumericBlockNumbers load the numeric block numbers from state accordingly
// to the provided from and to block number
func (f *NativeBlockHashBlockRangeFilter) GetNumericBlockNumbers(ctx context.Context, cfg Config, s types.StateInterface, e types.EthermanInterface, dbTx pgx.Tx) (uint64, uint64, types.Error) {
return getNumericBlockNumbers(ctx, s, e, &f.FromBlock, &f.ToBlock, cfg.MaxNativeBlockHashBlockRange, state.ErrMaxNativeBlockHashBlockRangeLimitExceeded, dbTx)
}
// getNumericBlockNumbers load the numeric block numbers from state accordingly
// to the provided from and to block number
func getNumericBlockNumbers(ctx context.Context, s types.StateInterface, e types.EthermanInterface, fromBlock, toBlock *types.BlockNumber, maxBlockRange uint64, maxBlockRangeErr error, dbTx pgx.Tx) (uint64, uint64, types.Error) {
var fromBlockNumber uint64 = 0
if fromBlock != nil {
fbn, rpcErr := fromBlock.GetNumericBlockNumber(ctx, s, e, dbTx)
if rpcErr != nil {
return 0, 0, rpcErr
}
fromBlockNumber = fbn
}
toBlockNumber, rpcErr := toBlock.GetNumericBlockNumber(ctx, s, e, dbTx)
if rpcErr != nil {
return 0, 0, rpcErr
}
if toBlockNumber < fromBlockNumber {
_, rpcErr := RPCErrorResponse(types.InvalidParamsErrorCode, state.ErrInvalidBlockRange.Error(), nil, false)
return 0, 0, rpcErr
}
blockRange := toBlockNumber - fromBlockNumber
if maxBlockRange > 0 && blockRange > maxBlockRange {
errMsg := fmt.Sprintf(maxBlockRangeErr.Error(), maxBlockRange)
_, rpcErr := RPCErrorResponse(types.InvalidParamsErrorCode, errMsg, nil, false)
return 0, 0, rpcErr
}
return fromBlockNumber, toBlockNumber, nil
}