github.com/iotexproject/iotex-core@v1.14.1-rc1/action/protocol/poll/blockmeta.go (about)

     1  // Copyright (c) 2020 IoTeX Foundation
     2  // This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
     3  // or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
     4  // This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
     5  
     6  package poll
     7  
     8  import (
     9  	"time"
    10  
    11  	"github.com/pkg/errors"
    12  	"google.golang.org/protobuf/proto"
    13  	"google.golang.org/protobuf/types/known/timestamppb"
    14  
    15  	"github.com/iotexproject/iotex-core/action/protocol/poll/blockmetapb"
    16  )
    17  
    18  // BlockMeta is a struct to store block metadata
    19  type BlockMeta struct {
    20  	Height   uint64
    21  	Producer string
    22  	MintTime time.Time
    23  }
    24  
    25  // NewBlockMeta constructs new blockmeta struct with given fieldss
    26  func NewBlockMeta(height uint64, producer string, mintTime time.Time) *BlockMeta {
    27  	return &BlockMeta{
    28  		Height:   height,
    29  		Producer: producer,
    30  		MintTime: mintTime.UTC(),
    31  	}
    32  }
    33  
    34  // Serialize serializes BlockMeta struct to bytes
    35  func (bm *BlockMeta) Serialize() ([]byte, error) {
    36  	pb, err := bm.Proto()
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  	return proto.Marshal(pb)
    41  }
    42  
    43  // Proto converts the BlockMeta struct to a protobuf message
    44  func (bm *BlockMeta) Proto() (*blockmetapb.BlockMeta, error) {
    45  	blkTime := timestamppb.New(bm.MintTime)
    46  	return &blockmetapb.BlockMeta{
    47  		BlockHeight:   bm.Height,
    48  		BlockProducer: bm.Producer,
    49  		BlockTime:     blkTime,
    50  	}, nil
    51  }
    52  
    53  // Deserialize deserializes bytes to blockMeta
    54  func (bm *BlockMeta) Deserialize(buf []byte) error {
    55  	epochMetapb := &blockmetapb.BlockMeta{}
    56  	if err := proto.Unmarshal(buf, epochMetapb); err != nil {
    57  		return errors.Wrap(err, "failed to unmarshal blocklist")
    58  	}
    59  	return bm.LoadProto(epochMetapb)
    60  }
    61  
    62  // LoadProto loads blockMeta from proto
    63  func (bm *BlockMeta) LoadProto(pb *blockmetapb.BlockMeta) error {
    64  	if err := pb.GetBlockTime().CheckValid(); err != nil {
    65  		return err
    66  	}
    67  	mintTime := pb.GetBlockTime().AsTime()
    68  	bm.Height = pb.GetBlockHeight()
    69  	bm.Producer = pb.GetBlockProducer()
    70  	bm.MintTime = mintTime.UTC()
    71  	return nil
    72  }