github.com/iotexproject/iotex-core@v1.14.1-rc1/blockindex/blockindex.go (about)

     1  // Copyright (c) 2019 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 blockindex
     7  
     8  import (
     9  	"math/big"
    10  
    11  	"github.com/pkg/errors"
    12  	"google.golang.org/protobuf/proto"
    13  
    14  	"github.com/iotexproject/iotex-core/blockindex/indexpb"
    15  	"github.com/iotexproject/iotex-core/pkg/util/byteutil"
    16  )
    17  
    18  type blockIndex struct {
    19  	hash      []byte
    20  	numAction uint32
    21  	tsfAmount *big.Int
    22  }
    23  
    24  // Hash returns the hash
    25  func (b *blockIndex) Hash() []byte {
    26  	return b.hash
    27  }
    28  
    29  // NumAction returns number of actions
    30  func (b *blockIndex) NumAction() uint32 {
    31  	return b.numAction
    32  }
    33  
    34  // TsfAmount returns transfer amount
    35  func (b *blockIndex) TsfAmount() *big.Int {
    36  	return b.tsfAmount
    37  }
    38  
    39  // Serialize into byte stream
    40  func (b *blockIndex) Serialize() []byte {
    41  	return byteutil.Must(proto.Marshal(b.toProto()))
    42  }
    43  
    44  // Desrialize from byte stream
    45  func (b *blockIndex) Deserialize(buf []byte) error {
    46  	pb := &indexpb.BlockIndex{}
    47  	if err := proto.Unmarshal(buf, pb); err != nil {
    48  		return err
    49  	}
    50  	return b.fromProto(pb)
    51  }
    52  
    53  // toProto converts to protobuf
    54  func (b *blockIndex) toProto() *indexpb.BlockIndex {
    55  	index := &indexpb.BlockIndex{
    56  		NumAction: b.numAction,
    57  		Hash:      b.hash,
    58  	}
    59  	if b.tsfAmount != nil {
    60  		index.TsfAmount = b.tsfAmount.Bytes()
    61  	}
    62  	return index
    63  }
    64  
    65  // fromProto converts from protobuf
    66  func (b *blockIndex) fromProto(pbIndex *indexpb.BlockIndex) error {
    67  	if pbIndex == nil {
    68  		return errors.New("empty protobuf")
    69  	}
    70  	b.numAction = pbIndex.NumAction
    71  	b.hash = nil
    72  	if len(pbIndex.Hash) > 0 {
    73  		b.hash = make([]byte, len(pbIndex.Hash))
    74  		copy(b.hash, pbIndex.Hash)
    75  	}
    76  	b.tsfAmount = big.NewInt(0)
    77  	if len(pbIndex.TsfAmount) > 0 {
    78  		b.tsfAmount.SetBytes(pbIndex.TsfAmount)
    79  	}
    80  	return nil
    81  }