-
Notifications
You must be signed in to change notification settings - Fork 2
/
parser.go
422 lines (351 loc) · 12.1 KB
/
parser.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package ces
import (
"bytes"
"context"
"encoding/hex"
"errors"
"fmt"
"log"
"strconv"
"strings"
"github.com/make-software/casper-go-sdk/v2/casper"
"github.com/make-software/casper-go-sdk/v2/rpc"
"github.com/make-software/casper-go-sdk/v2/types/clvalue"
"github.com/make-software/casper-go-sdk/v2/types/clvalue/cltype"
"github.com/make-software/casper-go-sdk/v2/types/key"
"golang.org/x/sync/errgroup"
)
var (
ErrFailedDeploy = errors.New("error: failed deploy, expected successful deploys")
ErrEventNameNotInSchema = errors.New("error: event name not found in Schema")
ErrFailedToParseContractEventSchema = errors.New("error: failed to parse contract event Schema")
ErrExpectContractStoredValue = errors.New("error: expect contract stored value")
ErrExpectCLValueStoredValue = errors.New("error: expect clValue stored value")
ErrMissingRequiredNamedKey = errors.New("error: missing required named key")
ErrNoEventPrefixInEvent = errors.New("error: no event_ prefix in event")
ErrNilDictionaryInTransform = errors.New("error: nil dictionary in transform")
ErrNotSmartContractAddressableEntity = errors.New("not SmartContract addressable entity type")
)
type NetworkVersion uint
const (
Casper1x NetworkVersion = iota
Casper2x
// Casper2xRC4 introduces smart contracts as AddressableEntities.
// In future versions, functionality will remain the same as in Casper1x.
Casper2xRC4
)
const (
eventSchemaNamedKey = "__events_schema"
eventNamedKey = "__events"
eventPrefix = "event_"
)
type (
EventParser struct {
casperClient casper.RPCClient
// key represent Uref from __events named key
contractsMetadata map[string]ContractMetadata
// version of the network used by parser
networkVersion NetworkVersion
}
EventName = string
EventMetadata struct {
Name string
Uref casper.Uref
Payload *bytes.Buffer
EventID uint
}
ContractMetadata struct {
Schemas Schemas
ContractHash casper.Hash
ContractPackageHash casper.Hash
EventsSchemaURef casper.Uref
EventsURef casper.Uref
}
)
func NewParserWithVersion(casperClient casper.RPCClient, contractHashes []casper.Hash, version NetworkVersion) (*EventParser, error) {
eventParser := EventParser{
casperClient: casperClient,
}
contractsMetadata, err := eventParser.loadContractsMetadata(contractHashes, version)
if err != nil {
return nil, err
}
return &EventParser{
casperClient: casperClient,
contractsMetadata: contractsMetadata,
networkVersion: version,
}, nil
}
func NewParser(casperClient casper.RPCClient, contractHashes []casper.Hash) (*EventParser, error) {
return NewParserWithVersion(casperClient, contractHashes, Casper2x)
}
// ParseExecutionResults accept casper.ExecutionResult analyze its transforms and trying to parse events according to stored contract schema
func (p *EventParser) ParseExecutionResults(executionResult casper.ExecutionResult) ([]ParseResult, error) {
if executionResult.ErrorMessage != nil {
return nil, ErrFailedDeploy
}
var results = make([]ParseResult, 0)
for transformIDx, transform := range executionResult.Effects {
if ok := transform.Kind.IsWriteCLValue(); !ok {
continue
}
eventMetadata, err := ParseEventMetadataFromTransform(transform)
if err != nil {
continue
}
contractMetadata, ok := p.contractsMetadata[eventMetadata.Uref.String()]
if !ok {
continue
}
parseResult := ParseResult{
Event: Event{
Name: eventMetadata.Name,
TransformID: uint(transformIDx),
EventID: eventMetadata.EventID,
},
}
eventSchema, ok := contractMetadata.Schemas[parseResult.Event.Name]
if !ok {
parseResult.Error = ErrEventNameNotInSchema
results = append(results, parseResult)
continue
}
rawData := eventMetadata.Payload.Bytes()
eventData, err := ParseEventDataFromSchemaBytes(eventSchema, eventMetadata.Payload)
if err != nil {
parseResult.Error = err
results = append(results, parseResult)
continue
}
parseResult.Event.ContractHash = contractMetadata.ContractHash
parseResult.Event.ContractPackageHash = contractMetadata.ContractPackageHash
parseResult.Event.RawData = hex.EncodeToString(rawData)
parseResult.Event.Data = eventData
results = append(results, parseResult)
}
return results, nil
}
func ParseEventMetadataFromTransform(transform casper.Transform) (EventMetadata, error) {
writeCLValue, err := transform.Kind.ParseAsWriteCLValue()
if err != nil {
return EventMetadata{}, err
}
if transform.Key.Dictionary == nil {
return EventMetadata{}, ErrNilDictionaryInTransform
}
rawBytes, err := writeCLValue.Value()
if err != nil {
return EventMetadata{}, err
}
if rawBytes.Any == nil {
return EventMetadata{}, err
}
dictionary, err := newDictionary(rawBytes.Any.Bytes())
if err != nil {
return EventMetadata{}, err
}
payload := bytes.NewBuffer(dictionary.DataToBytes())
eventNameWithPrefix, err := clvalue.FromBufferByType(payload, cltype.String)
if err != nil {
return EventMetadata{}, err
}
eventID, err := strconv.Atoi(dictionary.Key)
if err != nil {
return EventMetadata{}, err
}
return EventMetadata{
Name: strings.TrimPrefix(eventNameWithPrefix.String(), eventPrefix),
Uref: dictionary.Uref,
Payload: payload,
EventID: uint(eventID),
}, nil
}
// FetchContractSchemasBytes accept contract hash to fetch stored contract schema
func (p *EventParser) FetchContractSchemasBytes(contractHash casper.Hash) ([]byte, error) {
loadContractSchemasFromEntity := func(contractHash casper.Hash) (*rpc.QueryGlobalStateResult, error) {
entity, err := p.casperClient.GetLatestEntity(context.Background(), rpc.EntityIdentifier{
EntityAddr: &key.EntityAddr{
SmartContract: &contractHash,
},
})
if err != nil {
return nil, err
}
addressableEntity := entity.Entity.AddressableEntity
if addressableEntity != nil && addressableEntity.Entity.EntityKind.SmartContract != nil {
var eventSchemaUref string
for _, namedKey := range addressableEntity.NamedKeys {
if namedKey.Name == eventSchemaNamedKey {
eventSchemaUref = namedKey.Key.String()
break
}
}
schemasURefValue, err := p.casperClient.QueryGlobalStateByStateHash(context.Background(), nil, eventSchemaUref, nil)
if err != nil {
return nil, err
}
return &schemasURefValue, nil
}
return nil, ErrNotSmartContractAddressableEntity
}
var (
schemasURefValue *rpc.QueryGlobalStateResult
err error
)
if p.networkVersion == Casper2xRC4 {
schemasURefValue, err = loadContractSchemasFromEntity(contractHash)
if err != nil {
log.Println("Error on fetching schemas bytes from addressable entity: ", err)
}
}
if schemasURefValue == nil {
res, err := p.casperClient.QueryGlobalStateByStateHash(context.Background(), nil, fmt.Sprintf("hash-%s", contractHash.ToHex()), []string{eventSchemaNamedKey})
if err != nil {
return nil, err
}
schemasURefValue = &res
}
value := schemasURefValue.StoredValue.CLValue
if value == nil {
return nil, ErrExpectCLValueStoredValue
}
return value.Bytes()
}
func (p *EventParser) loadContractsMetadata(contractHashes []casper.Hash, version NetworkVersion) (map[string]ContractMetadata, error) {
stateRootHash, err := p.casperClient.GetStateRootHashLatest(context.Background())
if err != nil {
return nil, err
}
stateRootString := stateRootHash.StateRootHash.ToHex()
contractsSchemas := make(map[string]ContractMetadata, len(contractHashes))
metadatas := make(chan *ContractMetadata, len(contractHashes))
errGroup, ctx := errgroup.WithContext(context.Background())
loadMetadata := func(hash casper.Hash) {
errGroup.Go(func() error {
var contractMetadata *ContractMetadata
// try to load contract metadata as AddressableEntity in case of network version V2 RC4
if version == Casper2xRC4 {
contractMetadata, err = p.loadContractMetadatAsAddressableEntity(ctx, hash)
if err != nil {
log.Println("Error on trying to load contract metadata from addressable entity: ", err)
}
}
if contractMetadata == nil {
log.Println("Trying to load contract metadata from global state...")
// in case of error try to load metadata as stored contract
contractMetadata, err = p.loadContractMetadatAsStoredContract(ctx, hash, stateRootString)
if err != nil {
return err
}
}
schemas, err := LoadContractEventSchemas(p.casperClient, stateRootString, contractMetadata.EventsSchemaURef)
if err != nil {
return ErrFailedToParseContractEventSchema
}
contractMetadata.ContractHash = hash
contractMetadata.Schemas = schemas
metadatas <- contractMetadata
return nil
})
}
for _, hash := range contractHashes {
loadMetadata(hash)
}
if err = errGroup.Wait(); err != nil {
return nil, err
}
close(metadatas)
for contractMetadata := range metadatas {
contractsSchemas[contractMetadata.EventsURef.String()] = *contractMetadata
}
return contractsSchemas, nil
}
func LoadContractMetadataWithoutSchema(contractPackage casper.Hash, namedKeys casper.NamedKeys) (ContractMetadata, error) {
var (
eventsURefStr string
eventsSchemaURefStr string
)
for _, namedKey := range namedKeys {
switch namedKey.Name {
case eventNamedKey:
eventsURefStr = namedKey.Key.String()
case eventSchemaNamedKey:
eventsSchemaURefStr = namedKey.Key.String()
}
if eventsURefStr != "" && eventsSchemaURefStr != "" {
break
}
}
if eventsURefStr == "" || eventsSchemaURefStr == "" {
return ContractMetadata{}, ErrMissingRequiredNamedKey
}
eventsSchemaURef, err := casper.NewUref(eventsSchemaURefStr)
if err != nil {
return ContractMetadata{}, err
}
eventsURef, err := casper.NewUref(eventsURefStr)
if err != nil {
return ContractMetadata{}, err
}
return ContractMetadata{
ContractPackageHash: contractPackage,
EventsSchemaURef: eventsSchemaURef,
EventsURef: eventsURef,
}, nil
}
func LoadContractEventSchemas(casperClient casper.RPCClient, stateRootHash string, eventSchemaUref casper.Uref) (Schemas, error) {
schemasURefValue, err := casperClient.QueryGlobalStateByStateHash(context.Background(), &stateRootHash, eventSchemaUref.String(), nil)
if err != nil {
return nil, err
}
if schemasURefValue.StoredValue.CLValue == nil {
return nil, ErrExpectCLValueStoredValue
}
// We cannot parse CLValue based on the CLType from the Argument raw data, as it may contain an Any type
// which we do not know how to parse. Therefore, we should parse the raw bytes, ignore the clType field,
// and provide the hardcoded CLType with the cltype.Dynamic type instead of Any
hexBytes, err := schemasURefValue.StoredValue.CLValue.Bytes()
if err != nil {
return nil, err
}
return NewSchemasFromBytes(hexBytes)
}
func (p *EventParser) loadContractMetadatAsAddressableEntity(ctx context.Context, hash casper.Hash) (*ContractMetadata, error) {
entity, err := p.casperClient.GetLatestEntity(ctx, rpc.EntityIdentifier{
EntityAddr: &key.EntityAddr{
SmartContract: &hash,
},
})
if err != nil {
return nil, err
}
addressableEntity := entity.Entity.AddressableEntity
if addressableEntity != nil && addressableEntity.Entity.EntityKind.SmartContract != nil {
packageHash := addressableEntity.Entity.PackageHash
contractPackageHash, err := casper.NewHash(strings.TrimPrefix(packageHash, "package-"))
if err != nil {
return nil, err
}
contractMetadata, err := LoadContractMetadataWithoutSchema(contractPackageHash, addressableEntity.NamedKeys)
if err != nil {
return nil, err
}
return &contractMetadata, nil
}
return nil, ErrNotSmartContractAddressableEntity
}
func (p *EventParser) loadContractMetadatAsStoredContract(ctx context.Context, hash casper.Hash, stateRoot string) (*ContractMetadata, error) {
contractResult, err := p.casperClient.QueryGlobalStateByStateHash(context.Background(), &stateRoot, fmt.Sprintf("hash-%s", hash), nil)
if err != nil {
return nil, err
}
if contractResult.StoredValue.Contract == nil {
return nil, ErrExpectContractStoredValue
}
contract := contractResult.StoredValue.Contract
contractMetadata, err := LoadContractMetadataWithoutSchema(contract.ContractPackageHash.Hash, contract.NamedKeys)
if err != nil {
return nil, err
}
return &contractMetadata, nil
}