github.com/DFWallet/tendermint-cosmos@v0.0.2/types/block_meta.go (about)

     1  package types
     2  
     3  import (
     4  	"bytes"
     5  	"errors"
     6  	"fmt"
     7  
     8  	tmproto "github.com/DFWallet/tendermint-cosmos/proto/tendermint/types"
     9  )
    10  
    11  // BlockMeta contains meta information.
    12  type BlockMeta struct {
    13  	BlockID   BlockID `json:"block_id"`
    14  	BlockSize int     `json:"block_size"`
    15  	Header    Header  `json:"header"`
    16  	NumTxs    int     `json:"num_txs"`
    17  }
    18  
    19  // NewBlockMeta returns a new BlockMeta.
    20  func NewBlockMeta(block *Block, blockParts *PartSet) *BlockMeta {
    21  	return &BlockMeta{
    22  		BlockID:   BlockID{block.Hash(), blockParts.Header()},
    23  		BlockSize: block.Size(),
    24  		Header:    block.Header,
    25  		NumTxs:    len(block.Data.Txs),
    26  	}
    27  }
    28  
    29  func (bm *BlockMeta) ToProto() *tmproto.BlockMeta {
    30  	if bm == nil {
    31  		return nil
    32  	}
    33  
    34  	pb := &tmproto.BlockMeta{
    35  		BlockID:   bm.BlockID.ToProto(),
    36  		BlockSize: int64(bm.BlockSize),
    37  		Header:    *bm.Header.ToProto(),
    38  		NumTxs:    int64(bm.NumTxs),
    39  	}
    40  	return pb
    41  }
    42  
    43  func BlockMetaFromProto(pb *tmproto.BlockMeta) (*BlockMeta, error) {
    44  	if pb == nil {
    45  		return nil, errors.New("blockmeta is empty")
    46  	}
    47  
    48  	bm := new(BlockMeta)
    49  
    50  	bi, err := BlockIDFromProto(&pb.BlockID)
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  
    55  	h, err := HeaderFromProto(&pb.Header)
    56  	if err != nil {
    57  		return nil, err
    58  	}
    59  
    60  	bm.BlockID = *bi
    61  	bm.BlockSize = int(pb.BlockSize)
    62  	bm.Header = h
    63  	bm.NumTxs = int(pb.NumTxs)
    64  
    65  	return bm, bm.ValidateBasic()
    66  }
    67  
    68  // ValidateBasic performs basic validation.
    69  func (bm *BlockMeta) ValidateBasic() error {
    70  	if err := bm.BlockID.ValidateBasic(); err != nil {
    71  		return err
    72  	}
    73  	if !bytes.Equal(bm.BlockID.Hash, bm.Header.Hash()) {
    74  		return fmt.Errorf("expected BlockID#Hash and Header#Hash to be the same, got %X != %X",
    75  			bm.BlockID.Hash, bm.Header.Hash())
    76  	}
    77  	return nil
    78  }