Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend pasing logic with addressable entity #10

Merged
merged 4 commits into from
Sep 19, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
github.com/golang/mock v1.6.0
github.com/make-software/casper-go-sdk/v2 v2.0.1-beta1.0.20240725075941-fdac8c4ae070
github.com/stretchr/testify v1.8.2
golang.org/x/sync v0.6.0
)

require (
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLL
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
Expand Down
186 changes: 145 additions & 41 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,28 @@ import (
"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")
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")
)

const (
Expand Down Expand Up @@ -109,6 +114,7 @@ func (p *EventParser) ParseExecutionResults(executionResult casper.ExecutionResu
continue
}

rawData := eventMetadata.Payload.Bytes()
eventData, err := ParseEventDataFromSchemaBytes(eventSchema, eventMetadata.Payload)
if err != nil {
parseResult.Error = err
Expand All @@ -118,7 +124,7 @@ func (p *EventParser) ParseExecutionResults(executionResult casper.ExecutionResu

parseResult.Event.ContractHash = contractMetadata.ContractHash
parseResult.Event.ContractPackageHash = contractMetadata.ContractPackageHash
parseResult.Event.RawData = hex.EncodeToString(eventMetadata.Payload.Bytes())
parseResult.Event.RawData = hex.EncodeToString(rawData)
parseResult.Event.Data = eventData
results = append(results, parseResult)
}
Expand Down Expand Up @@ -171,22 +177,53 @@ func ParseEventMetadataFromTransform(transform casper.Transform) (EventMetadata,

// FetchContractSchemasBytes accept contract hash to fetch stored contract schema
func (p *EventParser) FetchContractSchemasBytes(contractHash casper.Hash) ([]byte, error) {
schemasURefValue, err := p.casperClient.QueryGlobalStateByStateHash(context.Background(), nil, fmt.Sprintf("hash-%s", contractHash.ToHex()), []string{eventSchemaNamedKey})
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 rpc.QueryGlobalStateResult{}, 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 rpc.QueryGlobalStateResult{}, err
}

return schemasURefValue, nil
}
return rpc.QueryGlobalStateResult{}, ErrNotSmartContractAddressableEntity
}

schemasURefValue, err := loadContractSchemasFromEntity(contractHash)
if err != nil {
return nil, err
log.Println("Error pn fetching schemas bytes from addressable entity: ", err)

schemasURefValue, err = p.casperClient.QueryGlobalStateByStateHash(context.Background(), nil, fmt.Sprintf("hash-%s", contractHash.ToHex()), []string{eventSchemaNamedKey})
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ZhmakAS, it probably would make more sense to provide the possibility to specify the version and use the dedicated approach for 1.5.x and 2.0.0. With fallbacks, we won't be able to use the parser efficiently in 1.5.x

if err != nil {
return nil, err
}
}

value := schemasURefValue.StoredValue.CLValue
if value == nil {
return nil, ErrExpectCLValueStoredValue
}

bytesData, err := value.Value()
if err != nil {
return nil, err
}

return bytesData.Any.Bytes(), nil
return value.Bytes()
}

func (p *EventParser) loadContractsMetadata(contractHashes []casper.Hash) (map[string]ContractMetadata, error) {
Expand All @@ -197,41 +234,59 @@ func (p *EventParser) loadContractsMetadata(contractHashes []casper.Hash) (map[s

stateRootString := stateRootHash.StateRootHash.ToHex()
contractsSchemas := make(map[string]ContractMetadata, len(contractHashes))
for _, hash := range contractHashes {
contractResult, err := p.casperClient.QueryGlobalStateByStateHash(context.Background(), &stateRootString, fmt.Sprintf("hash-%s", hash), nil)
if err != nil {
return nil, err
}

if contractResult.StoredValue.Contract == nil {
return nil, ErrExpectContractStoredValue
}

contractMetadata, err := LoadContractMetadataWithoutSchema(*contractResult.StoredValue.Contract)
if err != nil {
return nil, err
}
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
contractMetadata, err := p.loadContractMetadatAsAddressableEntity(ctx, hash)
if err != nil {
log.Println("Error on trying to load contract metadata from addressable entity: ", err)

// 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
})
}

schemas, err := LoadContractEventSchemas(p.casperClient, stateRootString, contractMetadata.EventsSchemaURef)
if err != nil {
return nil, ErrFailedToParseContractEventSchema
}
for _, hash := range contractHashes {
loadMetadata(hash)
}

contractMetadata.ContractHash = hash
contractMetadata.Schemas = schemas
contractsSchemas[contractMetadata.EventsURef.String()] = contractMetadata
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(contractResult casper.Contract) (ContractMetadata, error) {
func LoadContractMetadataWithoutSchema(contractPackage casper.Hash, namedKeys casper.NamedKeys) (ContractMetadata, error) {
var (
eventsURefStr string
eventsSchemaURefStr string
)

for _, namedKey := range contractResult.NamedKeys {
for _, namedKey := range namedKeys {
switch namedKey.Name {
case eventNamedKey:
eventsURefStr = namedKey.Key.String()
Expand Down Expand Up @@ -259,7 +314,7 @@ func LoadContractMetadataWithoutSchema(contractResult casper.Contract) (Contract
}

return ContractMetadata{
ContractPackageHash: contractResult.ContractPackageHash.Hash,
ContractPackageHash: contractPackage,
EventsSchemaURef: eventsSchemaURef,
EventsURef: eventsURef,
}, nil
Expand All @@ -284,3 +339,52 @@ func LoadContractEventSchemas(casperClient casper.RPCClient, stateRootHash strin
}
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
}
Loading
Loading