github.com/ava-labs/avalanchego@v1.11.11/vms/proposervm/block/parse.go (about) 1 // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. 2 // See the file LICENSE for licensing terms. 3 4 package block 5 6 import ( 7 "fmt" 8 "sync" 9 10 "github.com/ava-labs/avalanchego/ids" 11 ) 12 13 type ParseResult struct { 14 Block Block 15 Err error 16 } 17 18 // ParseBlocks parses the given raw blocks into tuples of (Block, error). 19 // Each ParseResult is returned in the same order as its corresponding bytes in the input. 20 func ParseBlocks(blks [][]byte, chainID ids.ID) []ParseResult { 21 results := make([]ParseResult, len(blks)) 22 23 var wg sync.WaitGroup 24 wg.Add(len(blks)) 25 26 for i, blk := range blks { 27 go func(i int, blkBytes []byte) { 28 defer wg.Done() 29 results[i].Block, results[i].Err = Parse(blkBytes, chainID) 30 }(i, blk) 31 } 32 33 wg.Wait() 34 35 return results 36 } 37 38 // Parse a block and verify that the signature attached to the block is valid 39 // for the certificate provided in the block. 40 func Parse(bytes []byte, chainID ids.ID) (Block, error) { 41 block, err := ParseWithoutVerification(bytes) 42 if err != nil { 43 return nil, err 44 } 45 return block, block.verify(chainID) 46 } 47 48 // ParseWithoutVerification parses a block without verifying that the signature 49 // on the block is correct. 50 func ParseWithoutVerification(bytes []byte) (Block, error) { 51 var block Block 52 parsedVersion, err := Codec.Unmarshal(bytes, &block) 53 if err != nil { 54 return nil, err 55 } 56 if parsedVersion != CodecVersion { 57 return nil, fmt.Errorf("expected codec version %d but got %d", CodecVersion, parsedVersion) 58 } 59 return block, block.initialize(bytes) 60 } 61 62 func ParseHeader(bytes []byte) (Header, error) { 63 header := statelessHeader{} 64 parsedVersion, err := Codec.Unmarshal(bytes, &header) 65 if err != nil { 66 return nil, err 67 } 68 if parsedVersion != CodecVersion { 69 return nil, fmt.Errorf("expected codec version %d but got %d", CodecVersion, parsedVersion) 70 } 71 header.bytes = bytes 72 return &header, nil 73 }