-
Notifications
You must be signed in to change notification settings - Fork 322
/
blockindex.go
81 lines (69 loc) · 1.93 KB
/
blockindex.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Copyright (c) 2019 IoTeX Foundation
// This source code is provided 'as is' and no warranties are given as to title or non-infringement, merchantability
// or fitness for purpose and, to the extent permitted by law, all liability for your use of the code is disclaimed.
// This source code is governed by Apache License 2.0 that can be found in the LICENSE file.
package blockindex
import (
"math/big"
"github.com/pkg/errors"
"google.golang.org/protobuf/proto"
"github.com/iotexproject/iotex-core/blockindex/indexpb"
"github.com/iotexproject/iotex-core/pkg/util/byteutil"
)
type blockIndex struct {
hash []byte
numAction uint32
tsfAmount *big.Int
}
// Hash returns the hash
func (b *blockIndex) Hash() []byte {
return b.hash
}
// NumAction returns number of actions
func (b *blockIndex) NumAction() uint32 {
return b.numAction
}
// TsfAmount returns transfer amount
func (b *blockIndex) TsfAmount() *big.Int {
return b.tsfAmount
}
// Serialize into byte stream
func (b *blockIndex) Serialize() []byte {
return byteutil.Must(proto.Marshal(b.toProto()))
}
// Desrialize from byte stream
func (b *blockIndex) Deserialize(buf []byte) error {
pb := &indexpb.BlockIndex{}
if err := proto.Unmarshal(buf, pb); err != nil {
return err
}
return b.fromProto(pb)
}
// toProto converts to protobuf
func (b *blockIndex) toProto() *indexpb.BlockIndex {
index := &indexpb.BlockIndex{
NumAction: b.numAction,
Hash: b.hash,
}
if b.tsfAmount != nil {
index.TsfAmount = b.tsfAmount.Bytes()
}
return index
}
// fromProto converts from protobuf
func (b *blockIndex) fromProto(pbIndex *indexpb.BlockIndex) error {
if pbIndex == nil {
return errors.New("empty protobuf")
}
b.numAction = pbIndex.NumAction
b.hash = nil
if len(pbIndex.Hash) > 0 {
b.hash = make([]byte, len(pbIndex.Hash))
copy(b.hash, pbIndex.Hash)
}
b.tsfAmount = big.NewInt(0)
if len(pbIndex.TsfAmount) > 0 {
b.tsfAmount.SetBytes(pbIndex.TsfAmount)
}
return nil
}