forked from stellar/stellar-rpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_events.go
333 lines (292 loc) · 8 KB
/
get_events.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
package protocol
import (
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"github.com/stellar/go/strkey"
"github.com/stellar/go/xdr"
)
const (
GetEventsMethodName = "getEvents"
MaxFiltersLimit = 5
MaxTopicsLimit = 5
MaxContractIDsLimit = 5
MinTopicCount = 1
MaxTopicCount = 4
)
type EventInfo struct {
EventType string `json:"type"`
Ledger int32 `json:"ledger"`
LedgerClosedAt string `json:"ledgerClosedAt"`
ContractID string `json:"contractId"`
ID string `json:"id"`
// Deprecated: PagingToken field is deprecated, please use Cursor at top level for pagination
PagingToken string `json:"pagingToken"`
InSuccessfulContractCall bool `json:"inSuccessfulContractCall"`
TransactionHash string `json:"txHash"`
// TopicXDR is a base64-encoded list of ScVals
TopicXDR []string `json:"topic,omitempty"`
TopicJSON []json.RawMessage `json:"topicJson,omitempty"`
// ValueXDR is a base64-encoded ScVal
ValueXDR string `json:"value,omitempty"`
ValueJSON json.RawMessage `json:"valueJson,omitempty"`
}
const (
EventTypeSystem = "system"
EventTypeContract = "contract"
EventTypeDiagnostic = "diagnostic"
)
func GetEventTypeFromEventTypeXDR() map[xdr.ContractEventType]string {
return map[xdr.ContractEventType]string{
xdr.ContractEventTypeSystem: EventTypeSystem,
xdr.ContractEventTypeContract: EventTypeContract,
xdr.ContractEventTypeDiagnostic: EventTypeDiagnostic,
}
}
func GetEventTypeXDRFromEventType() map[string]xdr.ContractEventType {
return map[string]xdr.ContractEventType{
EventTypeSystem: xdr.ContractEventTypeSystem,
EventTypeContract: xdr.ContractEventTypeContract,
EventTypeDiagnostic: xdr.ContractEventTypeDiagnostic,
}
}
func (e *EventFilter) Valid() error {
if err := e.EventType.valid(); err != nil {
return fmt.Errorf("filter type invalid: %w", err)
}
if len(e.ContractIDs) > MaxContractIDsLimit {
return errors.New("maximum 5 contract IDs per filter")
}
if len(e.Topics) > MaxTopicsLimit {
return errors.New("maximum 5 topics per filter")
}
for i, id := range e.ContractIDs {
_, err := strkey.Decode(strkey.VersionByteContract, id)
if err != nil {
return fmt.Errorf("contract ID %d invalid", i+1)
}
}
for i, topic := range e.Topics {
if err := topic.Valid(); err != nil {
return fmt.Errorf("topic %d invalid: %w", i+1, err)
}
}
return nil
}
type EventTypeSet map[string]interface{} //nolint:recvcheck
func (e EventTypeSet) valid() error {
for key := range e {
switch key {
case EventTypeSystem, EventTypeContract, EventTypeDiagnostic:
// ok
default:
return errors.New("if set, type must be either 'system', 'contract' or 'diagnostic'")
}
}
return nil
}
func (e *EventTypeSet) UnmarshalJSON(data []byte) error {
if len(data) == 0 {
*e = map[string]interface{}{}
return nil
}
var joined string
if err := json.Unmarshal(data, &joined); err != nil {
return err
}
*e = map[string]interface{}{}
if len(joined) == 0 {
return nil
}
for _, key := range strings.Split(joined, ",") {
(*e)[key] = nil
}
return nil
}
func (e EventTypeSet) MarshalJSON() ([]byte, error) {
keys := make([]string, 0, len(e))
for key := range e {
keys = append(keys, key)
}
return json.Marshal(strings.Join(keys, ","))
}
func (e EventTypeSet) Keys() []string {
keys := make([]string, 0, len(e))
for key := range e {
keys = append(keys, key)
}
return keys
}
func (e EventTypeSet) matches(event xdr.ContractEvent) bool {
if len(e) == 0 {
return true
}
_, ok := e[GetEventTypeFromEventTypeXDR()[event.Type]]
return ok
}
type EventFilter struct {
EventType EventTypeSet `json:"type,omitempty"`
ContractIDs []string `json:"contractIds,omitempty"`
Topics []TopicFilter `json:"topics,omitempty"`
}
type GetEventsRequest struct {
StartLedger uint32 `json:"startLedger,omitempty"`
EndLedger uint32 `json:"endLedger,omitempty"`
Filters []EventFilter `json:"filters"`
Pagination *PaginationOptions `json:"pagination,omitempty"`
Format string `json:"xdrFormat,omitempty"`
}
func (g *GetEventsRequest) Valid(maxLimit uint) error {
if err := IsValidFormat(g.Format); err != nil {
return err
}
// Validate the paging limit (if it exists)
if g.Pagination != nil && g.Pagination.Cursor != nil {
if g.StartLedger != 0 || g.EndLedger != 0 {
return errors.New("ledger ranges and cursor cannot both be set")
}
} else if g.StartLedger <= 0 {
return errors.New("startLedger must be positive")
}
if g.Pagination != nil && g.Pagination.Limit > maxLimit {
return fmt.Errorf("limit must not exceed %d", maxLimit)
}
// Validate filters
if len(g.Filters) > MaxFiltersLimit {
return errors.New("maximum 5 filters per request")
}
for i, filter := range g.Filters {
if err := filter.Valid(); err != nil {
return fmt.Errorf("filter %d invalid: %w", i+1, err)
}
}
return nil
}
func (g *GetEventsRequest) Matches(event xdr.DiagnosticEvent) bool {
if len(g.Filters) == 0 {
return true
}
for _, filter := range g.Filters {
if filter.Matches(event) {
return true
}
}
return false
}
func (e *EventFilter) Matches(event xdr.DiagnosticEvent) bool {
return e.EventType.matches(event.Event) && e.matchesContractIDs(event.Event) && e.matchesTopics(event.Event)
}
func (e *EventFilter) matchesContractIDs(event xdr.ContractEvent) bool {
if len(e.ContractIDs) == 0 {
return true
}
if event.ContractId == nil {
return false
}
needle := strkey.MustEncode(strkey.VersionByteContract, (*event.ContractId)[:])
return slices.Contains(e.ContractIDs, needle)
}
func (e *EventFilter) matchesTopics(event xdr.ContractEvent) bool {
if len(e.Topics) == 0 {
return true
}
v0, ok := event.Body.GetV0()
if !ok {
return false
}
for _, topicFilter := range e.Topics {
if topicFilter.Matches(v0.Topics) {
return true
}
}
return false
}
type TopicFilter []SegmentFilter
func (t TopicFilter) Valid() error {
if len(t) < MinTopicCount {
return errors.New("topic must have at least one segment")
}
if len(t) > MaxTopicCount {
return errors.New("topic cannot have more than 4 segments")
}
for i, segment := range t {
if err := segment.Valid(); err != nil {
return fmt.Errorf("segment %d invalid: %w", i+1, err)
}
}
return nil
}
// An event matches a topic filter iff:
// - the event has EXACTLY as many topic segments as the filter AND
// - each segment either: matches exactly OR is a wildcard.
func (t TopicFilter) Matches(event []xdr.ScVal) bool {
if len(event) != len(t) {
return false
}
for i, segmentFilter := range t {
if !segmentFilter.Matches(event[i]) {
return false
}
}
return true
}
type SegmentFilter struct {
Wildcard *string
ScVal *xdr.ScVal
}
func (s *SegmentFilter) Matches(segment xdr.ScVal) bool {
switch {
case s.Wildcard != nil && *s.Wildcard == "*":
return true
case s.ScVal != nil:
if !s.ScVal.Equals(segment) {
return false
}
default:
panic("invalid segmentFilter")
}
return true
}
func (s *SegmentFilter) Valid() error {
if s.Wildcard != nil && s.ScVal != nil {
return errors.New("cannot set both wildcard and scval")
}
if s.Wildcard == nil && s.ScVal == nil {
return errors.New("must set either wildcard or scval")
}
if s.Wildcard != nil && *s.Wildcard != "*" {
return errors.New("wildcard must be '*'")
}
return nil
}
func (s *SegmentFilter) UnmarshalJSON(p []byte) error {
s.Wildcard = nil
s.ScVal = nil
var tmp string
if err := json.Unmarshal(p, &tmp); err != nil {
return err
}
if tmp == "*" {
s.Wildcard = &tmp
} else {
var out xdr.ScVal
if err := xdr.SafeUnmarshalBase64(tmp, &out); err != nil {
return err
}
s.ScVal = &out
}
return nil
}
type PaginationOptions struct {
Cursor *Cursor `json:"cursor,omitempty"`
Limit uint `json:"limit,omitempty"`
}
type GetEventsResponse struct {
Events []EventInfo `json:"events"`
LatestLedger uint32 `json:"latestLedger"`
// Cursor represents last populated event ID if total events reach the limit
// or end of the search window
Cursor string `json:"cursor"`
}