github.com/koko1123/flow-go-1@v0.29.6/engine/common/rpc/convert/convert.go (about) 1 package convert 2 3 import ( 4 "encoding/json" 5 "errors" 6 "fmt" 7 8 "github.com/onflow/flow/protobuf/go/flow/entities" 9 "google.golang.org/protobuf/types/known/timestamppb" 10 11 "github.com/onflow/flow-go/crypto" 12 "github.com/onflow/flow-go/crypto/hash" 13 "github.com/koko1123/flow-go-1/ledger" 14 "github.com/koko1123/flow-go-1/model/flow" 15 "github.com/koko1123/flow-go-1/module/executiondatasync/execution_data" 16 "github.com/koko1123/flow-go-1/state/protocol" 17 "github.com/koko1123/flow-go-1/state/protocol/inmem" 18 ) 19 20 var ErrEmptyMessage = errors.New("protobuf message is empty") 21 var ValidChainIds = map[string]bool{ 22 flow.Mainnet.String(): true, 23 flow.Testnet.String(): true, 24 flow.Sandboxnet.String(): true, 25 flow.Benchnet.String(): true, 26 flow.Localnet.String(): true, 27 flow.Emulator.String(): true, 28 flow.BftTestnet.String(): true, 29 flow.MonotonicEmulator.String(): true, 30 } 31 32 func MessageToTransaction(m *entities.Transaction, chain flow.Chain) (flow.TransactionBody, error) { 33 if m == nil { 34 return flow.TransactionBody{}, ErrEmptyMessage 35 } 36 37 t := flow.NewTransactionBody() 38 39 proposalKey := m.GetProposalKey() 40 if proposalKey != nil { 41 proposalAddress, err := Address(proposalKey.GetAddress(), chain) 42 if err != nil { 43 return *t, err 44 } 45 t.SetProposalKey(proposalAddress, uint64(proposalKey.GetKeyId()), proposalKey.GetSequenceNumber()) 46 } 47 48 payer := m.GetPayer() 49 if payer != nil { 50 payerAddress, err := Address(payer, chain) 51 if err != nil { 52 return *t, err 53 } 54 t.SetPayer(payerAddress) 55 } 56 57 for _, authorizer := range m.GetAuthorizers() { 58 authorizerAddress, err := Address(authorizer, chain) 59 if err != nil { 60 return *t, err 61 } 62 t.AddAuthorizer(authorizerAddress) 63 } 64 65 for _, sig := range m.GetPayloadSignatures() { 66 addr, err := Address(sig.GetAddress(), chain) 67 if err != nil { 68 return *t, err 69 } 70 t.AddPayloadSignature(addr, uint64(sig.GetKeyId()), sig.GetSignature()) 71 } 72 73 for _, sig := range m.GetEnvelopeSignatures() { 74 addr, err := Address(sig.GetAddress(), chain) 75 if err != nil { 76 return *t, err 77 } 78 t.AddEnvelopeSignature(addr, uint64(sig.GetKeyId()), sig.GetSignature()) 79 } 80 81 t.SetScript(m.GetScript()) 82 t.SetArguments(m.GetArguments()) 83 t.SetReferenceBlockID(flow.HashToID(m.GetReferenceBlockId())) 84 t.SetGasLimit(m.GetGasLimit()) 85 86 return *t, nil 87 } 88 89 func TransactionsToMessages(transactions []*flow.TransactionBody) []*entities.Transaction { 90 transactionMessages := make([]*entities.Transaction, len(transactions)) 91 for i, t := range transactions { 92 transactionMessages[i] = TransactionToMessage(*t) 93 } 94 return transactionMessages 95 } 96 97 func TransactionToMessage(tb flow.TransactionBody) *entities.Transaction { 98 proposalKeyMessage := &entities.Transaction_ProposalKey{ 99 Address: tb.ProposalKey.Address.Bytes(), 100 KeyId: uint32(tb.ProposalKey.KeyIndex), 101 SequenceNumber: tb.ProposalKey.SequenceNumber, 102 } 103 104 authMessages := make([][]byte, len(tb.Authorizers)) 105 for i, auth := range tb.Authorizers { 106 authMessages[i] = auth.Bytes() 107 } 108 109 payloadSigMessages := make([]*entities.Transaction_Signature, len(tb.PayloadSignatures)) 110 111 for i, sig := range tb.PayloadSignatures { 112 payloadSigMessages[i] = &entities.Transaction_Signature{ 113 Address: sig.Address.Bytes(), 114 KeyId: uint32(sig.KeyIndex), 115 Signature: sig.Signature, 116 } 117 } 118 119 envelopeSigMessages := make([]*entities.Transaction_Signature, len(tb.EnvelopeSignatures)) 120 121 for i, sig := range tb.EnvelopeSignatures { 122 envelopeSigMessages[i] = &entities.Transaction_Signature{ 123 Address: sig.Address.Bytes(), 124 KeyId: uint32(sig.KeyIndex), 125 Signature: sig.Signature, 126 } 127 } 128 129 return &entities.Transaction{ 130 Script: tb.Script, 131 Arguments: tb.Arguments, 132 ReferenceBlockId: tb.ReferenceBlockID[:], 133 GasLimit: tb.GasLimit, 134 ProposalKey: proposalKeyMessage, 135 Payer: tb.Payer.Bytes(), 136 Authorizers: authMessages, 137 PayloadSignatures: payloadSigMessages, 138 EnvelopeSignatures: envelopeSigMessages, 139 } 140 } 141 142 func BlockHeaderToMessage(h *flow.Header, signerIDs flow.IdentifierList) (*entities.BlockHeader, error) { 143 id := h.ID() 144 145 t := timestamppb.New(h.Timestamp) 146 parentVoterIds := IdentifiersToMessages(signerIDs) 147 148 return &entities.BlockHeader{ 149 Id: id[:], 150 ParentId: h.ParentID[:], 151 Height: h.Height, 152 PayloadHash: h.PayloadHash[:], 153 Timestamp: t, 154 View: h.View, 155 ParentVoterIndices: h.ParentVoterIndices, 156 ParentVoterIds: parentVoterIds, 157 ParentVoterSigData: h.ParentVoterSigData, 158 ProposerId: h.ProposerID[:], 159 ProposerSigData: h.ProposerSigData, 160 ChainId: h.ChainID.String(), 161 }, nil 162 } 163 164 func MessageToBlockHeader(m *entities.BlockHeader) (*flow.Header, error) { 165 chainId, err := MessageToChainId(m.ChainId) 166 if err != nil { 167 return nil, fmt.Errorf("failed to convert ChainId: %w", err) 168 } 169 return &flow.Header{ 170 ParentID: MessageToIdentifier(m.ParentId), 171 Height: m.Height, 172 PayloadHash: MessageToIdentifier(m.PayloadHash), 173 Timestamp: m.Timestamp.AsTime(), 174 View: m.View, 175 ParentVoterIndices: m.ParentVoterIndices, 176 ParentVoterSigData: m.ParentVoterSigData, 177 ProposerID: MessageToIdentifier(m.ProposerId), 178 ProposerSigData: m.ProposerSigData, 179 ChainID: *chainId, 180 }, nil 181 } 182 183 // MessageToChainId checks chainId from enumeration to prevent a panic on Chain() being called 184 func MessageToChainId(m string) (*flow.ChainID, error) { 185 if !ValidChainIds[m] { 186 return nil, fmt.Errorf("invalid chainId %s: ", m) 187 } 188 chainId := flow.ChainID(m) 189 return &chainId, nil 190 } 191 192 func CollectionGuaranteesToMessages(c []*flow.CollectionGuarantee) []*entities.CollectionGuarantee { 193 cg := make([]*entities.CollectionGuarantee, len(c)) 194 for i, g := range c { 195 cg[i] = CollectionGuaranteeToMessage(g) 196 } 197 return cg 198 } 199 200 func MessagesToCollectionGuarantees(m []*entities.CollectionGuarantee) []*flow.CollectionGuarantee { 201 cg := make([]*flow.CollectionGuarantee, len(m)) 202 for i, g := range m { 203 cg[i] = MessageToCollectionGuarantee(g) 204 } 205 return cg 206 } 207 208 func BlockSealsToMessages(b []*flow.Seal) []*entities.BlockSeal { 209 seals := make([]*entities.BlockSeal, len(b)) 210 for i, s := range b { 211 seals[i] = BlockSealToMessage(s) 212 } 213 return seals 214 } 215 216 func MessagesToBlockSeals(m []*entities.BlockSeal) ([]*flow.Seal, error) { 217 seals := make([]*flow.Seal, len(m)) 218 for i, s := range m { 219 msg, err := MessageToBlockSeal(s) 220 if err != nil { 221 return nil, err 222 } 223 seals[i] = msg 224 } 225 return seals, nil 226 } 227 228 func ExecutionResultsToMessages(e []*flow.ExecutionResult) ([]*entities.ExecutionResult, error) { 229 execResults := make([]*entities.ExecutionResult, len(e)) 230 for i, execRes := range e { 231 parsedExecResult, err := ExecutionResultToMessage(execRes) 232 if err != nil { 233 return nil, err 234 } 235 execResults[i] = parsedExecResult 236 } 237 return execResults, nil 238 } 239 240 func MessagesToExecutionResults(m []*entities.ExecutionResult) ([]*flow.ExecutionResult, error) { 241 execResults := make([]*flow.ExecutionResult, len(m)) 242 for i, e := range m { 243 parsedExecResult, err := MessageToExecutionResult(e) 244 if err != nil { 245 return nil, fmt.Errorf("failed to convert message at index %d to execution result: %w", i, err) 246 } 247 execResults[i] = parsedExecResult 248 } 249 return execResults, nil 250 } 251 252 func BlockToMessage(h *flow.Block, signerIDs flow.IdentifierList) (*entities.Block, error) { 253 254 id := h.ID() 255 256 parentID := h.Header.ParentID 257 t := timestamppb.New(h.Header.Timestamp) 258 cg := CollectionGuaranteesToMessages(h.Payload.Guarantees) 259 260 seals := BlockSealsToMessages(h.Payload.Seals) 261 262 execResults, err := ExecutionResultsToMessages(h.Payload.Results) 263 if err != nil { 264 return nil, err 265 } 266 267 blockHeader, err := BlockHeaderToMessage(h.Header, signerIDs) 268 if err != nil { 269 return nil, err 270 } 271 272 bh := entities.Block{ 273 Id: id[:], 274 Height: h.Header.Height, 275 ParentId: parentID[:], 276 Timestamp: t, 277 CollectionGuarantees: cg, 278 BlockSeals: seals, 279 Signatures: [][]byte{h.Header.ParentVoterSigData}, 280 ExecutionReceiptMetaList: ExecutionResultMetaListToMessages(h.Payload.Receipts), 281 ExecutionResultList: execResults, 282 BlockHeader: blockHeader, 283 } 284 285 return &bh, nil 286 } 287 288 func BlockToMessageLight(h *flow.Block) *entities.Block { 289 id := h.ID() 290 291 parentID := h.Header.ParentID 292 t := timestamppb.New(h.Header.Timestamp) 293 cg := CollectionGuaranteesToMessages(h.Payload.Guarantees) 294 295 return &entities.Block{ 296 Id: id[:], 297 Height: h.Header.Height, 298 ParentId: parentID[:], 299 Timestamp: t, 300 CollectionGuarantees: cg, 301 Signatures: [][]byte{h.Header.ParentVoterSigData}, 302 } 303 } 304 305 func MessageToBlock(m *entities.Block) (*flow.Block, error) { 306 payload, err := PayloadFromMessage(m) 307 if err != nil { 308 return nil, fmt.Errorf("failed to extract payload data from message: %w", err) 309 } 310 header, err := MessageToBlockHeader(m.BlockHeader) 311 if err != nil { 312 return nil, fmt.Errorf("failed to convert block header: %w", err) 313 } 314 return &flow.Block{ 315 Header: header, 316 Payload: payload, 317 }, nil 318 } 319 320 func MessagesToExecutionResultMetaList(m []*entities.ExecutionReceiptMeta) flow.ExecutionReceiptMetaList { 321 execMetaList := make([]*flow.ExecutionReceiptMeta, len(m)) 322 for i, message := range m { 323 execMetaList[i] = &flow.ExecutionReceiptMeta{ 324 ExecutorID: MessageToIdentifier(message.ExecutorId), 325 ResultID: MessageToIdentifier(message.ResultId), 326 Spocks: MessagesToSignatures(message.Spocks), 327 ExecutorSignature: MessageToSignature(message.ExecutorSignature), 328 } 329 } 330 return execMetaList[:] 331 } 332 333 func ExecutionResultMetaListToMessages(e flow.ExecutionReceiptMetaList) []*entities.ExecutionReceiptMeta { 334 messageList := make([]*entities.ExecutionReceiptMeta, len(e)) 335 for i, execMeta := range e { 336 messageList[i] = &entities.ExecutionReceiptMeta{ 337 ExecutorId: IdentifierToMessage(execMeta.ExecutorID), 338 ResultId: IdentifierToMessage(execMeta.ResultID), 339 Spocks: SignaturesToMessages(execMeta.Spocks), 340 ExecutorSignature: MessageToSignature(execMeta.ExecutorSignature), 341 } 342 } 343 return messageList 344 } 345 346 func PayloadFromMessage(m *entities.Block) (*flow.Payload, error) { 347 cgs := MessagesToCollectionGuarantees(m.CollectionGuarantees) 348 seals, err := MessagesToBlockSeals(m.BlockSeals) 349 if err != nil { 350 return nil, err 351 } 352 receipts := MessagesToExecutionResultMetaList(m.ExecutionReceiptMetaList) 353 results, err := MessagesToExecutionResults(m.ExecutionResultList) 354 if err != nil { 355 return nil, err 356 } 357 return &flow.Payload{ 358 Guarantees: cgs, 359 Seals: seals, 360 Receipts: receipts, 361 Results: results, 362 }, nil 363 } 364 365 func CollectionGuaranteeToMessage(g *flow.CollectionGuarantee) *entities.CollectionGuarantee { 366 id := g.ID() 367 368 return &entities.CollectionGuarantee{ 369 CollectionId: id[:], 370 Signatures: [][]byte{g.Signature}, 371 ReferenceBlockId: IdentifierToMessage(g.ReferenceBlockID), 372 Signature: g.Signature, 373 SignerIndices: g.SignerIndices, 374 } 375 } 376 377 func MessageToCollectionGuarantee(m *entities.CollectionGuarantee) *flow.CollectionGuarantee { 378 return &flow.CollectionGuarantee{ 379 CollectionID: MessageToIdentifier(m.CollectionId), 380 ReferenceBlockID: MessageToIdentifier(m.ReferenceBlockId), 381 SignerIndices: m.SignerIndices, 382 Signature: MessageToSignature(m.Signature), 383 } 384 } 385 386 func MessagesToAggregatedSignatures(m []*entities.AggregatedSignature) []flow.AggregatedSignature { 387 parsedSignatures := make([]flow.AggregatedSignature, len(m)) 388 for i, message := range m { 389 parsedSignatures[i] = flow.AggregatedSignature{ 390 SignerIDs: MessagesToIdentifiers(message.SignerIds), 391 VerifierSignatures: MessagesToSignatures(message.VerifierSignatures), 392 } 393 } 394 return parsedSignatures 395 } 396 397 func AggregatedSignaturesToMessages(a []flow.AggregatedSignature) []*entities.AggregatedSignature { 398 parsedMessages := make([]*entities.AggregatedSignature, len(a)) 399 for i, sig := range a { 400 parsedMessages[i] = &entities.AggregatedSignature{ 401 SignerIds: IdentifiersToMessages(sig.SignerIDs), 402 VerifierSignatures: SignaturesToMessages(sig.VerifierSignatures), 403 } 404 } 405 return parsedMessages 406 } 407 408 func MessagesToSignatures(m [][]byte) []crypto.Signature { 409 signatures := make([]crypto.Signature, len(m)) 410 for i, message := range m { 411 signatures[i] = MessageToSignature(message) 412 } 413 return signatures 414 } 415 416 func MessageToSignature(m []byte) crypto.Signature { 417 return m[:] 418 } 419 420 func SignaturesToMessages(s []crypto.Signature) [][]byte { 421 messages := make([][]byte, len(s)) 422 for i, sig := range s { 423 messages[i] = SignatureToMessage(sig) 424 } 425 return messages 426 } 427 428 func SignatureToMessage(s crypto.Signature) []byte { 429 return s[:] 430 } 431 432 func BlockSealToMessage(s *flow.Seal) *entities.BlockSeal { 433 id := s.BlockID 434 result := s.ResultID 435 return &entities.BlockSeal{ 436 BlockId: id[:], 437 ExecutionReceiptId: result[:], 438 ExecutionReceiptSignatures: [][]byte{}, // filling seals signature with zero 439 FinalState: StateCommitmentToMessage(s.FinalState), 440 AggregatedApprovalSigs: AggregatedSignaturesToMessages(s.AggregatedApprovalSigs), 441 ResultId: IdentifierToMessage(s.ResultID), 442 } 443 } 444 445 func MessageToBlockSeal(m *entities.BlockSeal) (*flow.Seal, error) { 446 finalState, err := MessageToStateCommitment(m.FinalState) 447 if err != nil { 448 return nil, fmt.Errorf("failed to convert message to block seal: %w", err) 449 } 450 return &flow.Seal{ 451 BlockID: MessageToIdentifier(m.BlockId), 452 ResultID: MessageToIdentifier(m.ResultId), 453 FinalState: finalState, 454 AggregatedApprovalSigs: MessagesToAggregatedSignatures(m.AggregatedApprovalSigs), 455 }, nil 456 } 457 458 func CollectionToMessage(c *flow.Collection) (*entities.Collection, error) { 459 if c == nil || c.Transactions == nil { 460 return nil, fmt.Errorf("invalid collection") 461 } 462 463 transactionsIDs := make([][]byte, len(c.Transactions)) 464 for i, t := range c.Transactions { 465 id := t.ID() 466 transactionsIDs[i] = id[:] 467 } 468 469 collectionID := c.ID() 470 471 ce := &entities.Collection{ 472 Id: collectionID[:], 473 TransactionIds: transactionsIDs, 474 } 475 476 return ce, nil 477 } 478 479 func LightCollectionToMessage(c *flow.LightCollection) (*entities.Collection, error) { 480 if c == nil || c.Transactions == nil { 481 return nil, fmt.Errorf("invalid collection") 482 } 483 484 collectionID := c.ID() 485 486 return &entities.Collection{ 487 Id: collectionID[:], 488 TransactionIds: IdentifiersToMessages(c.Transactions), 489 }, nil 490 } 491 492 func EventToMessage(e flow.Event) *entities.Event { 493 return &entities.Event{ 494 Type: string(e.Type), 495 TransactionId: e.TransactionID[:], 496 TransactionIndex: e.TransactionIndex, 497 EventIndex: e.EventIndex, 498 Payload: e.Payload, 499 } 500 } 501 502 func MessageToAccount(m *entities.Account) (*flow.Account, error) { 503 if m == nil { 504 return nil, ErrEmptyMessage 505 } 506 507 accountKeys := make([]flow.AccountPublicKey, len(m.GetKeys())) 508 for i, key := range m.GetKeys() { 509 accountKey, err := MessageToAccountKey(key) 510 if err != nil { 511 return nil, err 512 } 513 514 accountKeys[i] = *accountKey 515 } 516 517 return &flow.Account{ 518 Address: flow.BytesToAddress(m.GetAddress()), 519 Balance: m.GetBalance(), 520 Keys: accountKeys, 521 Contracts: m.Contracts, 522 }, nil 523 } 524 525 func AccountToMessage(a *flow.Account) (*entities.Account, error) { 526 keys := make([]*entities.AccountKey, len(a.Keys)) 527 for i, k := range a.Keys { 528 messageKey, err := AccountKeyToMessage(k) 529 if err != nil { 530 return nil, err 531 } 532 keys[i] = messageKey 533 } 534 535 return &entities.Account{ 536 Address: a.Address.Bytes(), 537 Balance: a.Balance, 538 Code: nil, 539 Keys: keys, 540 Contracts: a.Contracts, 541 }, nil 542 } 543 544 func MessageToAccountKey(m *entities.AccountKey) (*flow.AccountPublicKey, error) { 545 if m == nil { 546 return nil, ErrEmptyMessage 547 } 548 549 sigAlgo := crypto.SigningAlgorithm(m.GetSignAlgo()) 550 hashAlgo := hash.HashingAlgorithm(m.GetHashAlgo()) 551 552 publicKey, err := crypto.DecodePublicKey(sigAlgo, m.GetPublicKey()) 553 if err != nil { 554 return nil, err 555 } 556 557 return &flow.AccountPublicKey{ 558 Index: int(m.GetIndex()), 559 PublicKey: publicKey, 560 SignAlgo: sigAlgo, 561 HashAlgo: hashAlgo, 562 Weight: int(m.GetWeight()), 563 SeqNumber: uint64(m.GetSequenceNumber()), 564 Revoked: m.GetRevoked(), 565 }, nil 566 } 567 568 func AccountKeyToMessage(a flow.AccountPublicKey) (*entities.AccountKey, error) { 569 publicKey := a.PublicKey.Encode() 570 return &entities.AccountKey{ 571 Index: uint32(a.Index), 572 PublicKey: publicKey, 573 SignAlgo: uint32(a.SignAlgo), 574 HashAlgo: uint32(a.HashAlgo), 575 Weight: uint32(a.Weight), 576 SequenceNumber: uint32(a.SeqNumber), 577 Revoked: a.Revoked, 578 }, nil 579 } 580 581 func MessagesToEvents(l []*entities.Event) []flow.Event { 582 events := make([]flow.Event, len(l)) 583 584 for i, m := range l { 585 events[i] = MessageToEvent(m) 586 } 587 588 return events 589 } 590 591 func MessageToEvent(m *entities.Event) flow.Event { 592 return flow.Event{ 593 Type: flow.EventType(m.GetType()), 594 TransactionID: flow.HashToID(m.GetTransactionId()), 595 TransactionIndex: m.GetTransactionIndex(), 596 EventIndex: m.GetEventIndex(), 597 Payload: m.GetPayload(), 598 } 599 } 600 601 func EventsToMessages(flowEvents []flow.Event) []*entities.Event { 602 events := make([]*entities.Event, len(flowEvents)) 603 for i, e := range flowEvents { 604 event := EventToMessage(e) 605 events[i] = event 606 } 607 return events 608 } 609 610 func IdentifierToMessage(i flow.Identifier) []byte { 611 return i[:] 612 } 613 614 func MessageToIdentifier(b []byte) flow.Identifier { 615 return flow.HashToID(b) 616 } 617 618 func StateCommitmentToMessage(s flow.StateCommitment) []byte { 619 return s[:] 620 } 621 622 func MessageToStateCommitment(bytes []byte) (sc flow.StateCommitment, err error) { 623 if len(bytes) != len(sc) { 624 return sc, fmt.Errorf("invalid state commitment length. got %d expected %d", len(bytes), len(sc)) 625 } 626 copy(sc[:], bytes) 627 return 628 } 629 630 func IdentifiersToMessages(l []flow.Identifier) [][]byte { 631 results := make([][]byte, len(l)) 632 for i, item := range l { 633 results[i] = IdentifierToMessage(item) 634 } 635 return results 636 } 637 638 func MessagesToIdentifiers(l [][]byte) []flow.Identifier { 639 results := make([]flow.Identifier, len(l)) 640 for i, item := range l { 641 results[i] = MessageToIdentifier(item) 642 } 643 return results 644 } 645 646 // SnapshotToBytes converts a `protocol.Snapshot` to bytes, encoded as JSON 647 func SnapshotToBytes(snapshot protocol.Snapshot) ([]byte, error) { 648 serializable, err := inmem.FromSnapshot(snapshot) 649 if err != nil { 650 return nil, err 651 } 652 653 data, err := json.Marshal(serializable.Encodable()) 654 if err != nil { 655 return nil, err 656 } 657 658 return data, nil 659 } 660 661 // BytesToInmemSnapshot converts an array of bytes to `inmem.Snapshot` 662 func BytesToInmemSnapshot(bytes []byte) (*inmem.Snapshot, error) { 663 var encodable inmem.EncodableSnapshot 664 err := json.Unmarshal(bytes, &encodable) 665 if err != nil { 666 return nil, fmt.Errorf("could not unmarshal decoded snapshot: %w", err) 667 } 668 669 return inmem.SnapshotFromEncodable(encodable), nil 670 } 671 672 func MessagesToChunkList(m []*entities.Chunk) (flow.ChunkList, error) { 673 parsedChunks := make(flow.ChunkList, len(m)) 674 for i, chunk := range m { 675 parsedChunk, err := MessageToChunk(chunk) 676 if err != nil { 677 return nil, fmt.Errorf("failed to parse message at index %d to chunk: %w", i, err) 678 } 679 parsedChunks[i] = parsedChunk 680 } 681 return parsedChunks, nil 682 } 683 684 func MessagesToServiceEventList(m []*entities.ServiceEvent) (flow.ServiceEventList, error) { 685 parsedServiceEvents := make(flow.ServiceEventList, len(m)) 686 for i, serviceEvent := range m { 687 parsedServiceEvent, err := MessageToServiceEvent(serviceEvent) 688 if err != nil { 689 return nil, fmt.Errorf("failed to parse service event at index %d from message: %w", i, err) 690 } 691 parsedServiceEvents[i] = *parsedServiceEvent 692 } 693 return parsedServiceEvents, nil 694 } 695 696 func MessageToExecutionResult(m *entities.ExecutionResult) (*flow.ExecutionResult, error) { 697 // convert Chunks 698 parsedChunks, err := MessagesToChunkList(m.Chunks) 699 if err != nil { 700 return nil, fmt.Errorf("failed to parse messages to ChunkList: %w", err) 701 } 702 // convert ServiceEvents 703 parsedServiceEvents, err := MessagesToServiceEventList(m.ServiceEvents) 704 if err != nil { 705 return nil, err 706 } 707 return &flow.ExecutionResult{ 708 PreviousResultID: MessageToIdentifier(m.PreviousResultId), 709 BlockID: MessageToIdentifier(m.BlockId), 710 Chunks: parsedChunks, 711 ServiceEvents: parsedServiceEvents, 712 ExecutionDataID: MessageToIdentifier(m.ExecutionDataId), 713 }, nil 714 } 715 716 func ExecutionResultToMessage(er *flow.ExecutionResult) (*entities.ExecutionResult, error) { 717 718 chunks := make([]*entities.Chunk, len(er.Chunks)) 719 720 for i, chunk := range er.Chunks { 721 chunks[i] = ChunkToMessage(chunk) 722 } 723 724 serviceEvents := make([]*entities.ServiceEvent, len(er.ServiceEvents)) 725 var err error 726 for i, serviceEvent := range er.ServiceEvents { 727 serviceEvents[i], err = ServiceEventToMessage(serviceEvent) 728 if err != nil { 729 return nil, fmt.Errorf("error while convering service event %d: %w", i, err) 730 } 731 } 732 733 return &entities.ExecutionResult{ 734 PreviousResultId: IdentifierToMessage(er.PreviousResultID), 735 BlockId: IdentifierToMessage(er.BlockID), 736 Chunks: chunks, 737 ServiceEvents: serviceEvents, 738 ExecutionDataId: IdentifierToMessage(er.ExecutionDataID), 739 }, nil 740 } 741 742 func ServiceEventToMessage(event flow.ServiceEvent) (*entities.ServiceEvent, error) { 743 744 bytes, err := json.Marshal(event.Event) 745 if err != nil { 746 return nil, fmt.Errorf("cannot marshal service event: %w", err) 747 } 748 749 return &entities.ServiceEvent{ 750 Type: event.Type, 751 Payload: bytes, 752 }, nil 753 } 754 755 func MessageToServiceEvent(m *entities.ServiceEvent) (*flow.ServiceEvent, error) { 756 var event interface{} 757 rawEvent := m.Payload 758 // map keys correctly 759 switch m.Type { 760 case flow.ServiceEventSetup: 761 setup := new(flow.EpochSetup) 762 err := json.Unmarshal(rawEvent, setup) 763 if err != nil { 764 return nil, fmt.Errorf("failed to marshal to EpochSetup event: %w", err) 765 } 766 event = setup 767 case flow.ServiceEventCommit: 768 commit := new(flow.EpochCommit) 769 err := json.Unmarshal(rawEvent, commit) 770 if err != nil { 771 return nil, fmt.Errorf("failed to marshal to EpochCommit event: %w", err) 772 } 773 event = commit 774 default: 775 return nil, fmt.Errorf("invalid event type: %s", m.Type) 776 } 777 return &flow.ServiceEvent{ 778 Type: m.Type, 779 Event: event, 780 }, nil 781 } 782 783 func ChunkToMessage(chunk *flow.Chunk) *entities.Chunk { 784 return &entities.Chunk{ 785 CollectionIndex: uint32(chunk.CollectionIndex), 786 StartState: StateCommitmentToMessage(chunk.StartState), 787 EventCollection: IdentifierToMessage(chunk.EventCollection), 788 BlockId: IdentifierToMessage(chunk.BlockID), 789 TotalComputationUsed: chunk.TotalComputationUsed, 790 NumberOfTransactions: uint32(chunk.NumberOfTransactions), 791 Index: chunk.Index, 792 EndState: StateCommitmentToMessage(chunk.EndState), 793 } 794 } 795 796 func MessageToChunk(m *entities.Chunk) (*flow.Chunk, error) { 797 startState, err := flow.ToStateCommitment(m.StartState) 798 if err != nil { 799 return nil, fmt.Errorf("failed to parse Message start state to Chunk: %w", err) 800 } 801 endState, err := flow.ToStateCommitment(m.EndState) 802 if err != nil { 803 return nil, fmt.Errorf("failed to parse Message end state to Chunk: %w", err) 804 } 805 chunkBody := flow.ChunkBody{ 806 CollectionIndex: uint(m.CollectionIndex), 807 StartState: startState, 808 EventCollection: MessageToIdentifier(m.EventCollection), 809 BlockID: MessageToIdentifier(m.BlockId), 810 TotalComputationUsed: m.TotalComputationUsed, 811 NumberOfTransactions: uint64(m.NumberOfTransactions), 812 } 813 return &flow.Chunk{ 814 ChunkBody: chunkBody, 815 Index: m.Index, 816 EndState: endState, 817 }, nil 818 } 819 820 func BlockExecutionDataToMessage(data *execution_data.BlockExecutionData) (*entities.BlockExecutionData, error) { 821 chunkExecutionDatas := make([]*entities.ChunkExecutionData, len(data.ChunkExecutionDatas)) 822 for i, chunk := range data.ChunkExecutionDatas { 823 chunkMessage, err := ChunkExecutionDataToMessage(chunk) 824 if err != nil { 825 return nil, err 826 } 827 chunkExecutionDatas[i] = chunkMessage 828 } 829 return &entities.BlockExecutionData{ 830 BlockId: IdentifierToMessage(data.BlockID), 831 ChunkExecutionData: chunkExecutionDatas, 832 }, nil 833 } 834 835 func ChunkExecutionDataToMessage(data *execution_data.ChunkExecutionData) (*entities.ChunkExecutionData, error) { 836 collection := &entities.ExecutionDataCollection{} 837 if data.Collection != nil { 838 collection = &entities.ExecutionDataCollection{ 839 Transactions: TransactionsToMessages(data.Collection.Transactions), 840 } 841 } 842 843 events := EventsToMessages(data.Events) 844 if len(events) == 0 { 845 events = nil 846 } 847 848 paths := make([][]byte, len(data.TrieUpdate.Paths)) 849 for i, path := range data.TrieUpdate.Paths { 850 paths[i] = path[:] 851 } 852 853 payloads := make([]*entities.Payload, len(data.TrieUpdate.Payloads)) 854 for i, payload := range data.TrieUpdate.Payloads { 855 key, err := payload.Key() 856 if err != nil { 857 return nil, err 858 } 859 keyParts := make([]*entities.KeyPart, len(key.KeyParts)) 860 for j, keyPart := range key.KeyParts { 861 keyParts[j] = &entities.KeyPart{ 862 Type: uint32(keyPart.Type), 863 Value: keyPart.Value, 864 } 865 } 866 payloads[i] = &entities.Payload{ 867 KeyPart: keyParts, 868 Value: payload.Value(), 869 } 870 } 871 872 trieUpdate := &entities.TrieUpdate{ 873 RootHash: data.TrieUpdate.RootHash[:], 874 Paths: paths, 875 Payloads: payloads, 876 } 877 878 return &entities.ChunkExecutionData{ 879 Collection: collection, 880 Events: events, 881 TrieUpdate: trieUpdate, 882 }, nil 883 } 884 885 func MessageToBlockExecutionData(m *entities.BlockExecutionData, chain flow.Chain) (*execution_data.BlockExecutionData, error) { 886 if m == nil { 887 return nil, ErrEmptyMessage 888 } 889 chunks := make([]*execution_data.ChunkExecutionData, len(m.ChunkExecutionData)) 890 for i, chunk := range m.GetChunkExecutionData() { 891 convertedChunk, err := MessageToChunkExecutionData(chunk, chain) 892 if err != nil { 893 return nil, err 894 } 895 chunks[i] = convertedChunk 896 } 897 898 return &execution_data.BlockExecutionData{ 899 BlockID: MessageToIdentifier(m.GetBlockId()), 900 ChunkExecutionDatas: chunks, 901 }, nil 902 } 903 904 func MessageToChunkExecutionData(m *entities.ChunkExecutionData, chain flow.Chain) (*execution_data.ChunkExecutionData, error) { 905 collection, err := messageToExecutionDataCollection(m.GetCollection(), chain) 906 if err != nil { 907 return nil, err 908 } 909 910 trieUpdate, err := messageToTrieUpdate(m.GetTrieUpdate()) 911 if err != nil { 912 return nil, err 913 } 914 915 events := MessagesToEvents(m.GetEvents()) 916 if len(events) == 0 { 917 events = nil 918 } 919 920 return &execution_data.ChunkExecutionData{ 921 Collection: collection, 922 Events: events, 923 TrieUpdate: trieUpdate, 924 }, nil 925 } 926 927 func messageToExecutionDataCollection(m *entities.ExecutionDataCollection, chain flow.Chain) (*flow.Collection, error) { 928 messages := m.GetTransactions() 929 transactions := make([]*flow.TransactionBody, len(messages)) 930 for i, message := range messages { 931 transaction, err := MessageToTransaction(message, chain) 932 if err != nil { 933 return nil, err 934 } 935 transactions[i] = &transaction 936 } 937 938 if len(transactions) == 0 { 939 return nil, nil 940 } 941 942 return &flow.Collection{Transactions: transactions}, nil 943 } 944 945 func messageToTrieUpdate(m *entities.TrieUpdate) (*ledger.TrieUpdate, error) { 946 rootHash, err := ledger.ToRootHash(m.GetRootHash()) 947 if err != nil { 948 return nil, err 949 } 950 951 paths := make([]ledger.Path, len(m.GetPaths())) 952 for i, path := range m.GetPaths() { 953 convertedPath, err := ledger.ToPath(path) 954 if err != nil { 955 return nil, err 956 } 957 paths[i] = convertedPath 958 } 959 960 payloads := make([]*ledger.Payload, len(m.Payloads)) 961 for i, payload := range m.GetPayloads() { 962 keyParts := make([]ledger.KeyPart, len(payload.GetKeyPart())) 963 for j, keypart := range payload.GetKeyPart() { 964 keyParts[j] = ledger.NewKeyPart(uint16(keypart.GetType()), keypart.GetValue()) 965 } 966 payloads[i] = ledger.NewPayload(ledger.NewKey(keyParts), payload.GetValue()) 967 } 968 969 return &ledger.TrieUpdate{ 970 RootHash: rootHash, 971 Paths: paths, 972 Payloads: payloads, 973 }, nil 974 }