github.com/MetalBlockchain/metalgo@v1.11.9/vms/platformvm/block/codec.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  	"errors"
     8  	"math"
     9  
    10  	"github.com/MetalBlockchain/metalgo/codec"
    11  	"github.com/MetalBlockchain/metalgo/codec/linearcodec"
    12  	"github.com/MetalBlockchain/metalgo/utils/wrappers"
    13  	"github.com/MetalBlockchain/metalgo/vms/platformvm/txs"
    14  )
    15  
    16  const CodecVersion = txs.CodecVersion
    17  
    18  var (
    19  	// GenesisCodec allows blocks of larger than usual size to be parsed.
    20  	// While this gives flexibility in accommodating large genesis blocks
    21  	// it must not be used to parse new, unverified blocks which instead
    22  	// must be processed by Codec
    23  	GenesisCodec codec.Manager
    24  
    25  	Codec codec.Manager
    26  )
    27  
    28  func init() {
    29  	c := linearcodec.NewDefault()
    30  	gc := linearcodec.NewDefault()
    31  
    32  	errs := wrappers.Errs{}
    33  	for _, c := range []linearcodec.Codec{c, gc} {
    34  		errs.Add(
    35  			RegisterApricotBlockTypes(c),
    36  			txs.RegisterUnsignedTxsTypes(c),
    37  			RegisterBanffBlockTypes(c),
    38  			txs.RegisterDUnsignedTxsTypes(c),
    39  		)
    40  	}
    41  
    42  	Codec = codec.NewDefaultManager()
    43  	GenesisCodec = codec.NewManager(math.MaxInt32)
    44  	errs.Add(
    45  		Codec.RegisterCodec(CodecVersion, c),
    46  		GenesisCodec.RegisterCodec(CodecVersion, gc),
    47  	)
    48  	if errs.Errored() {
    49  		panic(errs.Err)
    50  	}
    51  }
    52  
    53  // RegisterApricotBlockTypes allows registering relevant type of blocks package
    54  // in the right sequence. Following repackaging of platformvm package, a few
    55  // subpackage-level codecs were introduced, each handling serialization of
    56  // specific types.
    57  func RegisterApricotBlockTypes(targetCodec codec.Registry) error {
    58  	return errors.Join(
    59  		targetCodec.RegisterType(&ApricotProposalBlock{}),
    60  		targetCodec.RegisterType(&ApricotAbortBlock{}),
    61  		targetCodec.RegisterType(&ApricotCommitBlock{}),
    62  		targetCodec.RegisterType(&ApricotStandardBlock{}),
    63  		targetCodec.RegisterType(&ApricotAtomicBlock{}),
    64  	)
    65  }
    66  
    67  func RegisterBanffBlockTypes(targetCodec codec.Registry) error {
    68  	return errors.Join(
    69  		targetCodec.RegisterType(&BanffProposalBlock{}),
    70  		targetCodec.RegisterType(&BanffAbortBlock{}),
    71  		targetCodec.RegisterType(&BanffCommitBlock{}),
    72  		targetCodec.RegisterType(&BanffStandardBlock{}),
    73  	)
    74  }